You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@doris.apache.org by yi...@apache.org on 2026/01/09 05:52:37 UTC
(doris) branch branch-4.0 updated: Cherry-pick cloud snapshot related PRs to branch-4.0 (#59470)
This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-4.0
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/branch-4.0 by this push:
new e776dd4117b Cherry-pick cloud snapshot related PRs to branch-4.0 (#59470)
e776dd4117b is described below
commit e776dd4117bd31b3b66e66b80e7eb97ae3359353
Author: walter <ma...@selectdb.com>
AuthorDate: Fri Jan 9 13:52:29 2026 +0800
Cherry-pick cloud snapshot related PRs to branch-4.0 (#59470)
Co-authored-by: abmdocrt <li...@selectdb.com>
Co-authored-by: meiyi <me...@selectdb.com>
Co-authored-by: Yixuan Wang <wa...@selectdb.com>
Co-authored-by: deardeng <de...@selectdb.com>
Co-authored-by: Gavin Chou <ga...@selectdb.com>
---
be/src/cloud/cloud_meta_mgr.cpp | 3 +-
.../schema_cluster_snapshot_properties_scanner.cpp | 28 +-
.../schema_cluster_snapshots_scanner.cpp | 19 +-
.../exec/schema_scanner/schema_scanner_helper.cpp | 2 +-
be/src/exec/schema_scanner/schema_scanner_helper.h | 5 +-
cloud/CMakeLists.txt | 75 +-
cloud/cmake/install_fdb.cmake | 280 +++
cloud/src/common/bvars.cpp | 22 +-
cloud/src/common/bvars.h | 17 +
cloud/src/common/config.h | 46 +
cloud/src/common/stopwatch.h | 4 +
cloud/src/{recycler => common}/sync_executor.h | 0
cloud/src/common/util.cpp | 10 +-
cloud/src/meta-service/http_encode_key.cpp | 287 ++-
cloud/src/meta-service/meta_server.cpp | 188 ++
cloud/src/meta-service/meta_server.h | 51 +
cloud/src/meta-service/meta_service.cpp | 596 +++--
cloud/src/meta-service/meta_service.h | 32 +-
cloud/src/meta-service/meta_service_helper.h | 6 +-
cloud/src/meta-service/meta_service_http.cpp | 109 +-
cloud/src/meta-service/meta_service_job.cpp | 293 +--
cloud/src/meta-service/meta_service_partition.cpp | 196 +-
cloud/src/meta-service/meta_service_resource.cpp | 725 +++++--
cloud/src/meta-service/meta_service_snapshot.cpp | 44 +-
.../src/meta-service/meta_service_tablet_stats.cpp | 287 ++-
cloud/src/meta-service/meta_service_tablet_stats.h | 46 +-
cloud/src/meta-service/meta_service_txn.cpp | 255 ++-
cloud/src/meta-service/txn_lazy_committer.cpp | 660 +++---
cloud/src/meta-service/txn_lazy_committer.h | 23 +-
cloud/src/meta-store/CMakeLists.txt | 1 +
cloud/src/meta-store/blob_message.cpp | 178 ++
cloud/src/meta-store/blob_message.h | 111 +
cloud/src/meta-store/clone_chain_reader.cpp | 1338 ++++++++++++
.../{meta_reader.h => clone_chain_reader.h} | 140 +-
cloud/src/meta-store/keys.cpp | 601 +++++-
cloud/src/meta-store/keys.h | 214 +-
cloud/src/meta-store/mem_txn_kv.cpp | 98 +
cloud/src/meta-store/mem_txn_kv.h | 15 +
cloud/src/meta-store/meta_reader.cpp | 300 ++-
cloud/src/meta-store/meta_reader.h | 76 +-
cloud/src/meta-store/txn_kv.cpp | 81 +-
cloud/src/meta-store/txn_kv.h | 18 +-
cloud/src/meta-store/txn_kv_error.h | 2 +
cloud/src/recycler/azure_obj_client.cpp | 7 +
cloud/src/recycler/azure_obj_client.h | 3 +
cloud/src/recycler/checker.cpp | 10 +-
cloud/src/recycler/checker.h | 27 +-
cloud/src/recycler/checker_snapshot.cpp | 29 +
cloud/src/recycler/hdfs_accessor.cpp | 7 +
cloud/src/recycler/hdfs_accessor.h | 2 +
cloud/src/recycler/meta_checker.cpp | 575 ++---
cloud/src/recycler/meta_checker.h | 81 +-
cloud/src/recycler/obj_storage_client.h | 3 +
cloud/src/recycler/recycler.cpp | 680 +++++-
cloud/src/recycler/recycler.h | 89 +-
cloud/src/recycler/recycler_operation_log.cpp | 211 +-
cloud/src/recycler/recycler_service.cpp | 5 +-
cloud/src/recycler/recycler_snapshot.cpp | 21 +
cloud/src/recycler/s3_accessor.cpp | 17 +
cloud/src/recycler/s3_accessor.h | 2 +
cloud/src/recycler/s3_obj_client.cpp | 24 +
cloud/src/recycler/s3_obj_client.h | 3 +
cloud/src/recycler/snapshot_chain_compactor.cpp | 461 ++++
cloud/src/recycler/snapshot_chain_compactor.h | 111 +
cloud/src/recycler/snapshot_data_migrator.cpp | 369 ++++
cloud/src/recycler/snapshot_data_migrator.h | 110 +
.../src/recycler/snapshot_data_size_calculator.cpp | 453 ++++
cloud/src/recycler/storage_vault_accessor.h | 2 +
cloud/src/recycler/sync_executor.h | 131 +-
cloud/src/resource-manager/resource_manager.cpp | 64 +-
cloud/src/resource-manager/resource_manager.h | 8 +
cloud/src/snapshot/snapshot_manager.cpp | 79 +-
cloud/src/snapshot/snapshot_manager.h | 29 +-
cloud/test/CMakeLists.txt | 8 +
cloud/test/blob_message_test.cpp | 274 +++
cloud/test/clone_chain_reader_test.cpp | 2280 ++++++++++++++++++++
cloud/test/document_message_test.cpp | 23 +-
cloud/test/fdb_injection_test.cpp | 7 +-
cloud/test/http_encode_key_test.cpp | 426 ++++
cloud/test/keys_test.cpp | 389 +++-
cloud/test/mem_txn_kv_test.cpp | 288 +++
cloud/test/meta_reader_test.cpp | 500 +++++
cloud/test/meta_server_test.cpp | 232 +-
cloud/test/meta_service_http_test.cpp | 43 +-
cloud/test/meta_service_operation_log_test.cpp | 1496 +------------
cloud/test/meta_service_test.cpp | 775 ++++++-
cloud/test/meta_service_versioned_read_test.cpp | 31 +-
cloud/test/mock_accessor.h | 7 +
cloud/test/rate_limiter_test.cpp | 4 +
cloud/test/recycle_versioned_keys_test.cpp | 510 ++++-
cloud/test/recycler_operation_log_test.cpp | 561 ++++-
cloud/test/recycler_test.cpp | 88 +-
cloud/test/resource_test.cpp | 450 ++++
cloud/test/rpc_kv_bvar_test.cpp | 3 +
cloud/test/schema_kv_test.cpp | 100 +-
cloud/test/snapshot_data_size_calculator_test.cpp | 162 ++
cloud/test/txn_kv_test.cpp | 168 +-
cloud/test/txn_lazy_commit_test.cpp | 12 +-
.../main/java/org/apache/doris/common/Config.java | 22 +
.../org/apache/doris/alter/CloudRollupJobV2.java | 2 +-
.../apache/doris/alter/CloudSchemaChangeJobV2.java | 2 +-
.../main/java/org/apache/doris/catalog/Env.java | 4 +-
.../java/org/apache/doris/catalog/SchemaTable.java | 4 +-
.../doris/clone/DynamicPartitionScheduler.java | 2 +-
.../apache/doris/cloud/catalog/CloudPartition.java | 21 +-
.../cloud/datasource/CloudInternalCatalog.java | 37 +-
.../apache/doris/cloud/rpc/MetaServiceClient.java | 5 +
.../apache/doris/cloud/rpc/MetaServiceProxy.java | 4 +
.../apache/doris/cloud/storage/AzureRemote.java | 57 +
.../apache/doris/cloud/storage/DefaultRemote.java | 156 +-
.../org/apache/doris/cloud/storage/MockRemote.java | 8 +
.../org/apache/doris/cloud/storage/RemoteBase.java | 11 +
.../transaction/CloudGlobalTransactionMgr.java | 32 +-
.../apache/doris/datasource/InternalCatalog.java | 26 +-
.../AdminSetAutoClusterSnapshotCommand.java | 10 +-
...dminSetClusterSnapshotFeatureSwitchCommand.java | 3 +-
gensrc/proto/cloud.proto | 85 +-
.../doris/regression/suite/SuiteCluster.groovy | 68 +-
.../suites/cloud_p0/recycler/check_meta.groovy | 37 +
119 files changed, 17036 insertions(+), 3492 deletions(-)
diff --git a/be/src/cloud/cloud_meta_mgr.cpp b/be/src/cloud/cloud_meta_mgr.cpp
index 1eb71fc93fa..27c40853245 100644
--- a/be/src/cloud/cloud_meta_mgr.cpp
+++ b/be/src/cloud/cloud_meta_mgr.cpp
@@ -1638,6 +1638,7 @@ Status CloudMetaMgr::update_delete_bitmap(const CloudTablet& tablet, int64_t loc
if (next_visible_version > 0) {
req.set_next_visible_version(next_visible_version);
}
+ req.set_store_version(store_version);
bool write_v1 = store_version == 1 || store_version == 3;
bool write_v2 = store_version == 2 || store_version == 3;
@@ -2188,7 +2189,7 @@ Status CloudMetaMgr::list_snapshot(std::vector<SnapshotInfoPB>& snapshots) {
req.set_cloud_unique_id(config::cloud_unique_id);
req.set_include_aborted(true);
RETURN_IF_ERROR(retry_rpc("list snapshot", req, &res, &MetaService_Stub::list_snapshot));
- for (auto& snapshot : snapshots) {
+ for (auto& snapshot : res.snapshots()) {
snapshots.emplace_back(snapshot);
}
return Status::OK();
diff --git a/be/src/exec/schema_scanner/schema_cluster_snapshot_properties_scanner.cpp b/be/src/exec/schema_scanner/schema_cluster_snapshot_properties_scanner.cpp
index 59bac7d74ff..3eded9782b2 100644
--- a/be/src/exec/schema_scanner/schema_cluster_snapshot_properties_scanner.cpp
+++ b/be/src/exec/schema_scanner/schema_cluster_snapshot_properties_scanner.cpp
@@ -35,8 +35,8 @@ class Block;
} // namespace vectorized
std::vector<SchemaScanner::ColumnDesc> SchemaClusterSnapshotPropertiesScanner::_s_tbls_columns = {
- {"SNAPSHOT_ENABLED", TYPE_BOOLEAN, sizeof(int8_t), true},
- {"AUTO_SNAPSHOT_ENABLED", TYPE_BOOLEAN, sizeof(int8_t), true},
+ {"SNAPSHOT_ENABLED", TYPE_STRING, sizeof(StringRef), true},
+ {"AUTO_SNAPSHOT", TYPE_BOOLEAN, sizeof(int8_t), true},
{"MAX_RESERVED_SNAPSHOTS", TYPE_BIGINT, sizeof(int64_t), true},
{"SNAPSHOT_INTERVAL_SECONDS", TYPE_BIGINT, sizeof(int64_t), true},
};
@@ -73,10 +73,26 @@ Status SchemaClusterSnapshotPropertiesScanner::get_next_block_internal(vectorize
Status SchemaClusterSnapshotPropertiesScanner::_fill_block_impl(vectorized::Block* block) {
SCOPED_TIMER(_fill_block_timer);
- bool ready = _switch_status != cloud::SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
- bool enabled = _switch_status == cloud::SnapshotSwitchStatus::SNAPSHOT_SWITCH_ON;
- SchemaScannerHelper::insert_bool_value(0, ready, block);
- SchemaScannerHelper::insert_bool_value(1, enabled, block);
+ bool auto_snapshot_enabled =
+ _switch_status == cloud::SnapshotSwitchStatus::SNAPSHOT_SWITCH_ON &&
+ _max_reserved_snapshots > 0;
+ std::string_view snapshot_enable_status;
+ switch (_switch_status) {
+ case cloud::SnapshotSwitchStatus::SNAPSHOT_SWITCH_ON:
+ snapshot_enable_status = "YES";
+ break;
+ case cloud::SnapshotSwitchStatus::SNAPSHOT_SWITCH_OFF:
+ snapshot_enable_status = "NO";
+ break;
+ case cloud::SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED:
+ snapshot_enable_status = "DISABLED";
+ break;
+ default:
+ snapshot_enable_status = "UNKNOWN";
+ break;
+ }
+ SchemaScannerHelper::insert_string_value(0, snapshot_enable_status, block);
+ SchemaScannerHelper::insert_bool_value(1, auto_snapshot_enabled, block);
SchemaScannerHelper::insert_int64_value(2, _max_reserved_snapshots, block);
SchemaScannerHelper::insert_int64_value(3, _snapshot_interval_seconds, block);
return Status::OK();
diff --git a/be/src/exec/schema_scanner/schema_cluster_snapshots_scanner.cpp b/be/src/exec/schema_scanner/schema_cluster_snapshots_scanner.cpp
index b624960a4d2..fb83379b002 100644
--- a/be/src/exec/schema_scanner/schema_cluster_snapshots_scanner.cpp
+++ b/be/src/exec/schema_scanner/schema_cluster_snapshots_scanner.cpp
@@ -174,25 +174,12 @@ Status SchemaClusterSnapshotsScanner::_fill_block_impl(vectorized::Block* block)
}
// status
{
- std::string prepare_status = "SNAPSHOT_PREPARE";
- std::string normal_status = "SNAPSHOT_NORMAL";
- std::string aborted_status = "SNAPSHOT_ABORTED";
+ std::vector<std::string> status(row_num);
for (int i = 0; i < row_num; ++i) {
auto& snapshot = _snapshots[i];
if (snapshot.has_status()) {
- auto status = snapshot.status();
- std::string* value;
- if (status == cloud::SnapshotStatus::SNAPSHOT_PREPARE) {
- value = &prepare_status;
- } else if (status == cloud::SnapshotStatus::SNAPSHOT_NORMAL) {
- value = &normal_status;
- } else if (status == cloud::SnapshotStatus::SNAPSHOT_ABORTED) {
- value = &aborted_status;
- } else {
- return Status::InternalError("Unknown snapshot status: ",
- std::to_string(status));
- }
- strs[i] = StringRef(value->c_str(), value->size());
+ status[i] = SnapshotStatus_Name(snapshot.status());
+ strs[i] = StringRef(status[i].c_str(), status[i].size());
datas[i] = strs.data() + i;
} else {
datas[i] = nullptr;
diff --git a/be/src/exec/schema_scanner/schema_scanner_helper.cpp b/be/src/exec/schema_scanner/schema_scanner_helper.cpp
index 3e253aa7f95..c3d9ecfee9d 100644
--- a/be/src/exec/schema_scanner/schema_scanner_helper.cpp
+++ b/be/src/exec/schema_scanner/schema_scanner_helper.cpp
@@ -29,7 +29,7 @@
namespace doris {
-void SchemaScannerHelper::insert_string_value(int col_index, std::string str_val,
+void SchemaScannerHelper::insert_string_value(int col_index, std::string_view str_val,
vectorized::Block* block) {
vectorized::MutableColumnPtr mutable_col_ptr;
mutable_col_ptr = block->get_by_position(col_index).column->assume_mutable();
diff --git a/be/src/exec/schema_scanner/schema_scanner_helper.h b/be/src/exec/schema_scanner/schema_scanner_helper.h
index d2969b0b327..0ea67291834 100644
--- a/be/src/exec/schema_scanner/schema_scanner_helper.h
+++ b/be/src/exec/schema_scanner/schema_scanner_helper.h
@@ -20,7 +20,7 @@
#include <stdint.h>
-#include <string>
+#include <string_view>
#include <vector>
#include "cctz/time_zone.h"
@@ -34,7 +34,8 @@ class Block;
} // namespace vectorized
class SchemaScannerHelper {
public:
- static void insert_string_value(int col_index, std::string str_val, vectorized::Block* block);
+ static void insert_string_value(int col_index, std::string_view str_val,
+ vectorized::Block* block);
static void insert_datetime_value(int col_index, const std::vector<void*>& datas,
vectorized::Block* block);
static void insert_datetime_value(int col_index, int64_t timestamp, const cctz::time_zone& ctz,
diff --git a/cloud/CMakeLists.txt b/cloud/CMakeLists.txt
index 40e24ec1b45..1c3591610c8 100644
--- a/cloud/CMakeLists.txt
+++ b/cloud/CMakeLists.txt
@@ -394,67 +394,12 @@ if (ENABLE_INJECTION_POINT)
add_definitions(-DENABLE_INJECTION_POINT)
endif()
-# Add libs if needed, download to current dir -- ${BUILD_DIR}
-set(FDB_LIB "fdb_lib_7_1_23.tar.xz")
-if (ARCH_AARCH64)
- set(FDB_LIB "fdb_lib_7_1_57.aarch64.tar.xz")
-endif ()
-file(GLOB RELEASE_FILE_LIST LIST_DIRECTORIES false "/etc/*release*")
-execute_process(COMMAND "cat" ${RELEASE_FILE_LIST}
- RESULT_VARIABLE CAT_RET_CODE
- OUTPUT_VARIABLE CAT_RET_CONTENT)
-string(TOUPPER "${CAT_RET_CONTENT}" CAT_RET_CONTENT)
-
-if (ARCH_AARCH64)
- message("Centos OS")
- SET(OS_RELEASE "Centos")
- set(FDB_LIB_URL "https://doris-build.oss-cn-beijing.aliyuncs.com/thirdparty/fdb/aarch64/")
- string(APPEND FDB_LIB_URL "${FDB_LIB}")
- set(FDB_LIB_MD5SUM "2d01a431b7a7465077e4ae5520f89693")
-else ()
- if ("${CAT_RET_CONTENT}" MATCHES "UBUNTU")
- message("Ubuntu OS")
- SET(OS_RELEASE "Ubuntu")
- set(FDB_LIB_URL "https://doris-build.oss-cn-beijing.aliyuncs.com/thirdparty/fdb/ubuntu/")
- string(APPEND FDB_LIB_URL "${FDB_LIB}")
- set(FDB_LIB_MD5SUM "a00fe45da95cfac4e0caffa274bb2b30")
- else()
- # If it is not ubuntu, it is regarded as centos by default
- message("Centos OS")
- SET(OS_RELEASE "Centos")
- set(FDB_LIB_URL "https://doris-build.oss-cn-beijing.aliyuncs.com/thirdparty/fdb/centos/")
- string(APPEND FDB_LIB_URL "${FDB_LIB}")
- set(FDB_LIB_MD5SUM "f9839a564849c0232a351143b4340de0")
- endif()
-endif()
-
-if (NOT EXISTS "${THIRDPARTY_SRC}/${FDB_LIB}")
- file(MAKE_DIRECTORY ${THIRDPARTY_SRC})
- execute_process(COMMAND curl --retry 10 --retry-delay 2 --retry-max-time 30 ${FDB_LIB_URL}
- -o ${THIRDPARTY_SRC}/${FDB_LIB} -k
- RESULTS_VARIABLE DOWNLOAD_RET)
- if (NOT ${DOWNLOAD_RET} STREQUAL "0")
- execute_process(COMMAND "rm" "-rf" "${THIRDPARTY_SRC}/${FDB_LIB}")
- message(FATAL_ERROR "Failed to download dependency of fdb ${FDB_LIB_URL}, remove it")
- endif ()
-endif ()
-
-# Add fdb dependencies
-add_definitions(-DFDB_API_VERSION=710)
-if (NOT EXISTS ${THIRDPARTY_DIR}/include/foundationdb)
- execute_process(COMMAND "md5sum" "${THIRDPARTY_SRC}/${FDB_LIB}"
- RESULT_VARIABLE MD5SUM_RET_CODE
- OUTPUT_VARIABLE MD5SUM_CONTENT)
- if (NOT "${MD5SUM_CONTENT}" MATCHES "${FDB_LIB_MD5SUM}")
- execute_process(COMMAND "rm" "-rf" "${THIRDPARTY_SRC}/${FDB_LIB}")
- message(FATAL_ERROR "${THIRDPARTY_SRC}/${FDB_LIB} md5sum check failed, remove it")
- endif ()
- execute_process(COMMAND tar xf ${THIRDPARTY_SRC}/${FDB_LIB} -C ${THIRDPARTY_DIR}/)
-endif ()
-
# enable glog custom prefix
add_definitions(-DGLOG_CUSTOM_PREFIX_SUPPORT)
+set(FDB_VERSIONS "7.1.57" "7.3.69")
+set(FDB_DEFAULT_VERSION "7.1.57")
+include(install_fdb)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lfdb_c -L${THIRDPARTY_DIR}/lib")
set(DORIS_CLOUD_LIBS
@@ -556,3 +501,17 @@ install(FILES
GROUP_READ GROUP_WRITE GROUP_EXECUTE
WORLD_READ WORLD_EXECUTE
DESTINATION ${OUTPUT_DIR}/lib)
+
+foreach(version ${FDB_VERSIONS})
+ if (version STREQUAL ${FDB_DEFAULT_VERSION})
+ continue()
+ endif()
+
+ string(REPLACE "." "_" version_underscored ${version})
+ install(FILES
+ ${FDB_INSTALL_DIR_${version_underscored}}/lib64/libfdb_c.so
+ PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE
+ GROUP_READ GROUP_WRITE GROUP_EXECUTE
+ WORLD_READ WORLD_EXECUTE
+ DESTINATION ${OUTPUT_DIR}/lib/fdb/${version}/libfdb_c.so)
+endforeach()
diff --git a/cloud/cmake/install_fdb.cmake b/cloud/cmake/install_fdb.cmake
new file mode 100644
index 00000000000..67fceb16e69
--- /dev/null
+++ b/cloud/cmake/install_fdb.cmake
@@ -0,0 +1,280 @@
+# 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.
+
+# ============================================================================
+# FDB Library Configuration
+# ============================================================================
+# Configuration format:
+# FDB_CONFIG_${version}_${arch}_${os}_FILE - Tarball filename
+# FDB_CONFIG_${version}_${arch}_${os}_MD5 - MD5 checksum
+# FDB_CONFIG_${version}_${arch}_${os}_URL - Base download URL
+# FDB_CONFIG_${version}_API_VERSION - FDB API version (e.g., 710)
+#
+# Supported combinations:
+# - version: 7_1_23, 7_1_57
+# - arch: AMD64, AARCH64
+# - os: UBUNTU, CENTOS (all uppercase)
+# ============================================================================
+
+# Version 7.1.23 Configuration
+set(FDB_CONFIG_7_1_23_API_VERSION "710")
+
+# Version 7.1.23 - AMD64 - UBUNTU
+set(FDB_CONFIG_7_1_23_AMD64_UBUNTU_FILE "fdb_lib_7_1_23.tar.xz")
+set(FDB_CONFIG_7_1_23_AMD64_UBUNTU_MD5 "a00fe45da95cfac4e0caffa274bb2b30")
+set(FDB_CONFIG_7_1_23_AMD64_UBUNTU_URL "https://doris-build.oss-cn-beijing.aliyuncs.com/thirdparty/fdb/ubuntu/")
+
+# Version 7.1.23 - AMD64 - CENTOS
+set(FDB_CONFIG_7_1_23_AMD64_CENTOS_FILE "fdb_lib_7_1_23.tar.xz")
+set(FDB_CONFIG_7_1_23_AMD64_CENTOS_MD5 "f9839a564849c0232a351143b4340de0")
+set(FDB_CONFIG_7_1_23_AMD64_CENTOS_URL "https://doris-build.oss-cn-beijing.aliyuncs.com/thirdparty/fdb/centos/")
+
+# Version 7.1.57 Configuration
+set(FDB_CONFIG_7_1_57_API_VERSION "710")
+
+# Version 7.1.57 - AARCH64 - CENTOS
+set(FDB_CONFIG_7_1_57_AARCH64_CENTOS_FILE "fdb_lib_7_1_57.aarch64.tar.xz")
+set(FDB_CONFIG_7_1_57_AARCH64_CENTOS_MD5 "2d01a431b7a7465077e4ae5520f89693")
+set(FDB_CONFIG_7_1_57_AARCH64_CENTOS_URL "https://doris-build.oss-cn-beijing.aliyuncs.com/thirdparty/fdb/aarch64/")
+
+# Version 7.1.57 - AMD64 - UBUNTU
+set(FDB_CONFIG_7_1_57_AMD64_UBUNTU_FILE "fdb_lib_7_1_57.tar.xz")
+set(FDB_CONFIG_7_1_57_AMD64_UBUNTU_MD5 "5a4aec35de0e041b952a3e39078f327a")
+set(FDB_CONFIG_7_1_57_AMD64_UBUNTU_URL "https://doris-build.oss-cn-beijing.aliyuncs.com/thirdparty/fdb/amd64/")
+
+# Version 7.1.57 - AMD64 - CENTOS
+set(FDB_CONFIG_7_1_57_AMD64_CENTOS_FILE "fdb_lib_7_1_57.tar.xz")
+set(FDB_CONFIG_7_1_57_AMD64_CENTOS_MD5 "5a4aec35de0e041b952a3e39078f327a")
+set(FDB_CONFIG_7_1_57_AMD64_CENTOS_URL "https://doris-build.oss-cn-beijing.aliyuncs.com/thirdparty/fdb/amd64/")
+
+# Version 7.3.69 Configuration
+set(FDB_CONFIG_7_3_69_API_VERSION "730")
+
+# Version 7.3.69 - AARCH64 - CENTOS
+set(FDB_CONFIG_7_3_69_AARCH64_CENTOS_FILE "fdb_lib_7_3_69.tar.xz")
+set(FDB_CONFIG_7_3_69_AARCH64_CENTOS_MD5 "7c6c676b41c70ef31eca617de7879364")
+set(FDB_CONFIG_7_3_69_AARCH64_CENTOS_URL "https://doris-build.oss-cn-beijing.aliyuncs.com/thirdparty/fdb/aarch64/")
+
+# Version 7.3.69 - AMD64 - UBUNTU
+set(FDB_CONFIG_7_3_69_AMD64_UBUNTU_FILE "fdb_lib_7_3_69.tar.xz")
+set(FDB_CONFIG_7_3_69_AMD64_UBUNTU_MD5 "5454db8a8aaa4bcc580c1a40d1171f61")
+set(FDB_CONFIG_7_3_69_AMD64_UBUNTU_URL "https://doris-build.oss-cn-beijing.aliyuncs.com/thirdparty/fdb/amd64/")
+
+# Version 7.3.69 - AMD64 - CENTOS
+set(FDB_CONFIG_7_3_69_AMD64_CENTOS_FILE "fdb_lib_7_3_69.tar.xz")
+set(FDB_CONFIG_7_3_69_AMD64_CENTOS_MD5 "5454db8a8aaa4bcc580c1a40d1171f61")
+set(FDB_CONFIG_7_3_69_AMD64_CENTOS_URL "https://doris-build.oss-cn-beijing.aliyuncs.com/thirdparty/fdb/amd64/")
+
+# ============================================================================
+# Detect OS (run once)
+# ============================================================================
+
+if (NOT DEFINED FDB_OS_DETECTED)
+ file(GLOB RELEASE_FILE_LIST LIST_DIRECTORIES false "/etc/*release*")
+ execute_process(COMMAND "cat" ${RELEASE_FILE_LIST}
+ RESULT_VARIABLE CAT_RET_CODE
+ OUTPUT_VARIABLE CAT_RET_CONTENT)
+ string(TOUPPER "${CAT_RET_CONTENT}" CAT_RET_CONTENT)
+
+ if ("${CAT_RET_CONTENT}" MATCHES "UBUNTU")
+ set(FDB_OS_RELEASE "UBUNTU" CACHE INTERNAL "Detected OS for FDB")
+ else()
+ # If it is not ubuntu, it is regarded as centos by default
+ set(FDB_OS_RELEASE "CENTOS" CACHE INTERNAL "Detected OS for FDB")
+ endif()
+
+ set(FDB_OS_DETECTED TRUE CACHE INTERNAL "OS detection flag")
+ message(STATUS "Detected OS: ${FDB_OS_RELEASE}")
+endif()
+
+# ============================================================================
+# Function: Download and Setup FDB Library
+# ============================================================================
+# Downloads, verifies, and extracts a specific version of FDB library
+#
+# Parameters:
+# version - FDB version in format like "7_1_23" or "7_1_57"
+#
+# Exports:
+# FDB_INSTALL_DIR_${version} - Installation directory for this version
+# FDB_LIB_SO_${version} - Path to libfdb_c.so for this version
+# ============================================================================
+
+function(download_and_setup_fdb version)
+ # Determine architecture
+ if (ARCH_AARCH64)
+ set(fdb_arch "AARCH64")
+ else()
+ set(fdb_arch "AMD64")
+ endif()
+
+ # Construct configuration variable names
+ set(config_prefix "FDB_CONFIG_${version}_${fdb_arch}_${FDB_OS_RELEASE}")
+ set(fdb_file_var "${config_prefix}_FILE")
+ set(fdb_md5_var "${config_prefix}_MD5")
+ set(fdb_url_var "${config_prefix}_URL")
+ set(fdb_api_version_var "FDB_CONFIG_${version}_API_VERSION")
+
+ # Check if all required configurations exist
+ set(missing_configs "")
+ if (NOT DEFINED ${fdb_file_var})
+ list(APPEND missing_configs ${fdb_file_var})
+ endif()
+ if (NOT DEFINED ${fdb_md5_var})
+ list(APPEND missing_configs ${fdb_md5_var})
+ endif()
+ if (NOT DEFINED ${fdb_url_var})
+ list(APPEND missing_configs ${fdb_url_var})
+ endif()
+ if (NOT DEFINED ${fdb_api_version_var})
+ list(APPEND missing_configs ${fdb_api_version_var})
+ endif()
+
+ if (missing_configs)
+ message(FATAL_ERROR "FDB version ${version} is missing required configurations for "
+ "architecture ${fdb_arch} and OS ${FDB_OS_RELEASE}:\n"
+ " Missing variables: ${missing_configs}\n"
+ " Please add the following configurations:\n"
+ " ${fdb_file_var}\n"
+ " ${fdb_md5_var}\n"
+ " ${fdb_url_var}\n"
+ " ${fdb_api_version_var}")
+ endif()
+
+ # Get configuration values
+ set(fdb_lib ${${fdb_file_var}})
+ set(fdb_md5 ${${fdb_md5_var}})
+ set(fdb_url ${${fdb_url_var}})
+
+ string(APPEND fdb_url "${fdb_lib}")
+
+ # Set version-specific installation directory
+ string(REPLACE "_" "." version_dotted ${version})
+ set(install_dir "${THIRDPARTY_DIR}/lib/fdb/${version_dotted}")
+ set(lib_so "${install_dir}/lib64/libfdb_c.so")
+
+ # Download FDB library if not exists
+ if (NOT EXISTS "${THIRDPARTY_SRC}/${fdb_lib}")
+ message(STATUS "Downloading FDB library from ${fdb_url}")
+ file(MAKE_DIRECTORY ${THIRDPARTY_SRC})
+ execute_process(COMMAND curl --retry 10 --retry-delay 2 --retry-max-time 30 ${fdb_url}
+ -o ${THIRDPARTY_SRC}/${fdb_lib} -k
+ RESULTS_VARIABLE download_ret)
+ if (NOT ${download_ret} STREQUAL "0")
+ execute_process(COMMAND "rm" "-rf" "${THIRDPARTY_SRC}/${fdb_lib}")
+ message(FATAL_ERROR "Failed to download dependency of fdb ${fdb_url}, remove it")
+ endif ()
+ endif ()
+
+ if (NOT EXISTS ${install_dir}/include/foundationdb)
+ execute_process(COMMAND "md5sum" "${THIRDPARTY_SRC}/${fdb_lib}"
+ RESULT_VARIABLE md5sum_ret_code
+ OUTPUT_VARIABLE md5sum_content)
+ if (NOT "${md5sum_content}" MATCHES "${fdb_md5}")
+ execute_process(COMMAND "rm" "-rf" "${THIRDPARTY_SRC}/${fdb_lib}")
+ message(FATAL_ERROR "${THIRDPARTY_SRC}/${fdb_lib} md5sum check failed, remove it")
+ endif ()
+
+ make_directory(${install_dir})
+ execute_process(COMMAND tar xf ${THIRDPARTY_SRC}/${fdb_lib} -C ${install_dir})
+ endif ()
+
+ # Export version-specific API version to parent scope
+ set(api_version_var "FDB_CONFIG_${version}_API_VERSION")
+ if (DEFINED ${api_version_var})
+ set(FDB_API_VERSION_${version} "${${api_version_var}}" PARENT_SCOPE)
+ endif()
+
+ # Export to parent scope
+ set(FDB_INSTALL_DIR_${version} "${install_dir}" PARENT_SCOPE)
+ set(FDB_LIB_SO_${version} "${lib_so}" PARENT_SCOPE)
+
+ message(STATUS "FDB ${version_dotted} installation directory: ${install_dir}")
+endfunction()
+
+# ============================================================================
+# Function: Setup Default FDB Library
+# ============================================================================
+# Sets up the default FDB library for static linking
+#
+# Parameters:
+# version - FDB version to use as default (e.g., "7_1_23")
+#
+# Exports:
+# FDB_INSTALL_DIR - Installation directory for default version
+# FDB_LIB_SO - Path to libfdb_c.so for default version
+# ============================================================================
+
+function(setup_default_fdb version)
+ string(REPLACE "_" "." version_dotted ${version})
+
+ # Ensure the version has been downloaded and set up
+ if (NOT DEFINED FDB_INSTALL_DIR_${version})
+ message(FATAL_ERROR "FDB version ${version_dotted} has not been downloaded. Call download_and_setup_fdb first.")
+ endif()
+
+ set(FDB_INSTALL_DIR "${FDB_INSTALL_DIR_${version}}")
+ set(FDB_LIB_SO "${FDB_LIB_SO_${version}}")
+
+ # Set default FDB paths to parent scope
+ set(FDB_INSTALL_DIR "${FDB_INSTALL_DIR_${version}}" PARENT_SCOPE)
+ set(FDB_LIB_SO "${FDB_LIB_SO_${version}}" PARENT_SCOPE)
+
+ # Install the default FDB library
+ execute_process(COMMAND "rm" "-rf" "${THIRDPARTY_DIR}/include/foundationdb")
+ execute_process(COMMAND "rm" "-rf" "${THIRDPARTY_DIR}/lib64/libfdb_c.so")
+ execute_process(COMMAND "cp" "-r" "${FDB_INSTALL_DIR}/include/foundationdb" "${THIRDPARTY_DIR}/include/foundationdb")
+ execute_process(COMMAND "cp" "${FDB_INSTALL_DIR}/lib64/libfdb_c.so" "${THIRDPARTY_DIR}/lib64/libfdb_c.so")
+
+ # Set FDB API version for the default version
+ set(api_version_var "FDB_CONFIG_${version}_API_VERSION")
+ if (DEFINED ${api_version_var})
+ set(fdb_api_version "${${api_version_var}}")
+ add_definitions(-DFDB_API_VERSION=${fdb_api_version})
+ message(STATUS "Default FDB API version: ${fdb_api_version}")
+ else()
+ message(WARNING "FDB API version not defined for version ${version_dotted}")
+ endif()
+endfunction()
+
+function(install_fdb_library target_dir)
+ install(FILES
+ ${THIRDPARTY_DIR}/lib/libfdb_c.so
+ PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE
+ GROUP_READ GROUP_WRITE GROUP_EXECUTE
+ WORLD_READ WORLD_EXECUTE
+ DESTINATION ${OUTPUT_DIR}/lib)
+endfunction()
+
+# ============================================================================
+# Main Execution
+# ============================================================================
+
+# Download and setup all specified FDB versions
+foreach (version IN LISTS FDB_VERSIONS)
+ string(REPLACE "." "_" version_underscored ${version})
+ download_and_setup_fdb(${version_underscored})
+endforeach()
+
+# Select the default FDB version
+string(REPLACE "." "_" FDB_DEFAULT_VERSION_UNDERSCORED ${FDB_DEFAULT_VERSION})
+setup_default_fdb(${FDB_DEFAULT_VERSION_UNDERSCORED})
+
+# Note: To add more FDB versions, call download_and_setup_fdb with other versions:
+# Example:
+# download_and_setup_fdb("7_1_57")
+# # Access via: ${FDB_INSTALL_DIR_7_1_57} and ${FDB_LIB_SO_7_1_57}
diff --git a/cloud/src/common/bvars.cpp b/cloud/src/common/bvars.cpp
index dc567b6dad8..11f63234ffb 100644
--- a/cloud/src/common/bvars.cpp
+++ b/cloud/src/common/bvars.cpp
@@ -101,6 +101,7 @@ BvarLatencyRecorderWithTag g_bvar_ms_set_cluster_status("ms", "set_cluster_statu
BvarLatencyRecorderWithTag g_bvar_ms_check_kv("ms", "check_kv");
BvarLatencyRecorderWithTag g_bvar_ms_get_schema_dict("ms", "get_schema_dict");
BvarLatencyRecorderWithTag g_bvar_ms_begin_snapshot("ms", "begin_snapshot");
+BvarLatencyRecorderWithTag g_bvar_ms_update_snapshot("ms", "update_snapshot");
BvarLatencyRecorderWithTag g_bvar_ms_commit_snapshot("ms", "commit_snapshot");
BvarLatencyRecorderWithTag g_bvar_ms_abort_snapshot("ms", "abort_snapshot");
BvarLatencyRecorderWithTag g_bvar_ms_drop_snapshot("ms", "drop_snapshot");
@@ -115,7 +116,12 @@ BvarLatencyRecorderWithStatus<60> g_bvar_ms_txn_commit_with_tablet_count("ms", "
MBvarLatencyRecorderWithStatus<60> g_bvar_instance_txn_commit_with_partition_count("instance", "txn_commit_with_partition_count", {"instance_id"});
MBvarLatencyRecorderWithStatus<60> g_bvar_instance_txn_commit_with_tablet_count("instance", "txn_commit_with_tablet_count", {"instance_id"});
-
+bvar::LatencyRecorder g_bvar_ms_scan_instance_update("ms", "scan_instance_update");
+bvar::LatencyRecorder g_bvar_txn_lazy_committer_waiting_duration("txn_lazy_committer", "waiting");
+bvar::LatencyRecorder g_bvar_txn_lazy_committer_committing_duration("txn_lazy_committer", "committing");
+bvar::LatencyRecorder g_bvar_txn_lazy_committer_commit_partition_duration("txn_lazy_committer", "commit_partition");
+bvar::Adder<int64_t> g_bvar_txn_lazy_committer_submitted("txn_lazy_committer", "submitted");
+bvar::Adder<int64_t> g_bvar_txn_lazy_committer_finished("txn_lazy_committer", "finished");
// recycler's bvars
// TODO: use mbvar for per instance, https://github.com/apache/brpc/blob/master/docs/cn/mbvar_c++.md
@@ -158,11 +164,17 @@ mBvarStatus<double> g_bvar_recycler_instance_recycle_time_per_resource("recycler
// represents the bytes of resources that can be recycled per ms
mBvarStatus<double> g_bvar_recycler_instance_recycle_bytes_per_ms("recycler_instance_recycle_bytes_per_ms", {"instance_id", "resource_type"});
+BvarStatusWithTag<int64_t> g_bvar_recycler_batch_delete_rowset_plan_count(
+ "recycler", "batch_delete_rowset_plan_count");
+BvarStatusWithTag<int64_t> g_bvar_recycler_batch_delete_failures(
+ "recycler", "batch_delete_failures");
+
// txn_kv's bvars
bvar::LatencyRecorder g_bvar_txn_kv_get("txn_kv", "get");
bvar::LatencyRecorder g_bvar_txn_kv_range_get("txn_kv", "range_get");
bvar::LatencyRecorder g_bvar_txn_kv_put("txn_kv", "put");
bvar::LatencyRecorder g_bvar_txn_kv_commit("txn_kv", "commit");
+bvar::LatencyRecorder g_bvar_txn_kv_watch_key("txn_kv", "watch_key");
bvar::LatencyRecorder g_bvar_txn_kv_atomic_set_ver_key("txn_kv", "atomic_set_ver_key");
bvar::LatencyRecorder g_bvar_txn_kv_atomic_set_ver_value("txn_kv", "atomic_set_ver_value");
bvar::LatencyRecorder g_bvar_txn_kv_atomic_add("txn_kv", "atomic_add");
@@ -418,6 +430,10 @@ mBvarInt64Adder g_bvar_rpc_kv_get_txn_id_get_counter("rpc_kv_get_txn_id_get_coun
mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_get_counter("rpc_kv_begin_snapshot_get_counter",{"instance_id"});
mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_put_counter("rpc_kv_begin_snapshot_put_counter",{"instance_id"});
mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_del_counter("rpc_kv_begin_snapshot_del_counter",{"instance_id"});
+// update snapshot
+mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_get_counter("rpc_kv_update_snapshot_get_counter",{"instance_id"});
+mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_put_counter("rpc_kv_update_snapshot_put_counter",{"instance_id"});
+mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_del_counter("rpc_kv_update_snapshot_del_counter",{"instance_id"});
// commit_snapshot
mBvarInt64Adder g_bvar_rpc_kv_commit_snapshot_get_counter("rpc_kv_commit_snapshot_get_counter",{"instance_id"});
mBvarInt64Adder g_bvar_rpc_kv_commit_snapshot_put_counter("rpc_kv_commit_snapshot_put_counter",{"instance_id"});
@@ -617,6 +633,10 @@ mBvarStatus<int64_t> g_bvar_fdb_kv_ranges_count("fdb_kv_ranges_count", {"categor
mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_get_bytes("rpc_kv_begin_snapshot_get_bytes",{"instance_id"});
mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_put_bytes("rpc_kv_begin_snapshot_put_bytes",{"instance_id"});
mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_del_bytes("rpc_kv_begin_snapshot_del_bytes",{"instance_id"});
+// update snapshot
+mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_get_bytes("rpc_kv_update_snapshot_get_bytes",{"instance_id"});
+mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_put_bytes("rpc_kv_update_snapshot_put_bytes",{"instance_id"});
+mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_del_bytes("rpc_kv_update_snapshot_del_bytes",{"instance_id"});
// commit_snapshot
mBvarInt64Adder g_bvar_rpc_kv_commit_snapshot_get_bytes("rpc_kv_commit_snapshot_get_bytes",{"instance_id"});
mBvarInt64Adder g_bvar_rpc_kv_commit_snapshot_put_bytes("rpc_kv_commit_snapshot_put_bytes",{"instance_id"});
diff --git a/cloud/src/common/bvars.h b/cloud/src/common/bvars.h
index 94494acc650..bda68cd1a0b 100644
--- a/cloud/src/common/bvars.h
+++ b/cloud/src/common/bvars.h
@@ -613,6 +613,7 @@ extern BvarLatencyRecorderWithTag g_bvar_ms_get_txn_id;
extern BvarLatencyRecorderWithTag g_bvar_ms_check_kv;
extern BvarLatencyRecorderWithTag g_bvar_ms_get_schema_dict;
extern BvarLatencyRecorderWithTag g_bvar_ms_begin_snapshot;
+extern BvarLatencyRecorderWithTag g_bvar_ms_update_snapshot;
extern BvarLatencyRecorderWithTag g_bvar_ms_commit_snapshot;
extern BvarLatencyRecorderWithTag g_bvar_ms_abort_snapshot;
extern BvarLatencyRecorderWithTag g_bvar_ms_drop_snapshot;
@@ -624,6 +625,12 @@ extern BvarLatencyRecorderWithStatus<60> g_bvar_ms_txn_commit_with_tablet_count;
extern BvarLatencyRecorderWithStatus<60> g_bvar_ms_txn_commit_with_partition_count;
extern MBvarLatencyRecorderWithStatus<60> g_bvar_instance_txn_commit_with_partition_count;
extern MBvarLatencyRecorderWithStatus<60> g_bvar_instance_txn_commit_with_tablet_count;
+extern bvar::LatencyRecorder g_bvar_ms_scan_instance_update;
+extern bvar::LatencyRecorder g_bvar_txn_lazy_committer_waiting_duration;
+extern bvar::LatencyRecorder g_bvar_txn_lazy_committer_committing_duration;
+extern bvar::LatencyRecorder g_bvar_txn_lazy_committer_commit_partition_duration;
+extern bvar::Adder<int64_t> g_bvar_txn_lazy_committer_submitted;
+extern bvar::Adder<int64_t> g_bvar_txn_lazy_committer_finished;
// recycler's bvars
extern BvarStatusWithTag<int64_t> g_bvar_recycler_recycle_index_earlest_ts;
@@ -654,11 +661,15 @@ extern mBvarIntAdder g_bvar_recycler_instance_recycle_round;
extern mBvarStatus<double> g_bvar_recycler_instance_recycle_time_per_resource;
extern mBvarStatus<double> g_bvar_recycler_instance_recycle_bytes_per_ms;
+extern BvarStatusWithTag<int64_t> g_bvar_recycler_batch_delete_rowset_plan_count;
+extern BvarStatusWithTag<int64_t> g_bvar_recycler_batch_delete_failures;
+
// txn_kv's bvars
extern bvar::LatencyRecorder g_bvar_txn_kv_get;
extern bvar::LatencyRecorder g_bvar_txn_kv_range_get;
extern bvar::LatencyRecorder g_bvar_txn_kv_put;
extern bvar::LatencyRecorder g_bvar_txn_kv_commit;
+extern bvar::LatencyRecorder g_bvar_txn_kv_watch_key;
extern bvar::LatencyRecorder g_bvar_txn_kv_atomic_set_ver_key;
extern bvar::LatencyRecorder g_bvar_txn_kv_atomic_set_ver_value;
extern bvar::LatencyRecorder g_bvar_txn_kv_atomic_add;
@@ -857,6 +868,9 @@ extern mBvarInt64Adder g_bvar_rpc_kv_get_txn_id_get_counter;
extern mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_get_counter;
extern mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_put_counter;
extern mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_del_counter;
+extern mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_get_counter;
+extern mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_put_counter;
+extern mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_del_counter;
extern mBvarInt64Adder g_bvar_rpc_kv_commit_snapshot_get_counter;
extern mBvarInt64Adder g_bvar_rpc_kv_commit_snapshot_put_counter;
extern mBvarInt64Adder g_bvar_rpc_kv_commit_snapshot_del_counter;
@@ -992,6 +1006,9 @@ extern mBvarInt64Adder g_bvar_rpc_kv_get_txn_id_get_bytes;
extern mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_get_bytes;
extern mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_put_bytes;
extern mBvarInt64Adder g_bvar_rpc_kv_begin_snapshot_del_bytes;
+extern mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_get_bytes;
+extern mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_put_bytes;
+extern mBvarInt64Adder g_bvar_rpc_kv_update_snapshot_del_bytes;
extern mBvarInt64Adder g_bvar_rpc_kv_commit_snapshot_get_bytes;
extern mBvarInt64Adder g_bvar_rpc_kv_commit_snapshot_put_bytes;
extern mBvarInt64Adder g_bvar_rpc_kv_commit_snapshot_del_bytes;
diff --git a/cloud/src/common/config.h b/cloud/src/common/config.h
index 45241859ee8..7171b9e2afe 100644
--- a/cloud/src/common/config.h
+++ b/cloud/src/common/config.h
@@ -30,6 +30,10 @@ CONF_Int32(brpc_idle_timeout_sec, "-1");
CONF_String(hostname, "");
CONF_String(fdb_cluster, "xxx:yyy@127.0.0.1:4500");
CONF_String(fdb_cluster_file_path, "./conf/fdb.cluster");
+CONF_Bool(enable_fdb_external_client_directory, "true");
+// The directory path of external foundationdb client library.
+// eg: /path/to/dir1:/path/to/dir2:...
+CONF_String(fdb_external_client_directory, "");
CONF_String(http_token, "greedisgood9999");
// use volatile mem kv for test. MUST NOT be `true` in production environment.
CONF_Bool(use_mem_kv, "false");
@@ -120,6 +124,9 @@ CONF_Bool(force_immediate_recycle, "false");
CONF_mBool(enable_mow_job_key_check, "false");
+// Strip key bounds in recycle rowset meta emitted by compaction to shrink op log size
+CONF_Bool(enable_recycle_rowset_strip_key_bounds, "true");
+
CONF_mBool(enable_restore_job_check, "false");
CONF_mBool(enable_tablet_stats_key_check, "false");
@@ -129,6 +136,8 @@ CONF_mBool(enable_meta_key_check, "false");
CONF_mBool(enable_version_key_check, "false");
CONF_mBool(enable_meta_rowset_key_check, "false");
CONF_mBool(enable_snapshot_check, "false");
+CONF_mBool(enable_mvcc_meta_key_check, "false");
+CONF_mBool(enable_mvcc_meta_check, "false");
CONF_mInt64(mow_job_key_check_expiration_diff_seconds, "600"); // 10min
@@ -290,7 +299,11 @@ CONF_mInt64(max_txn_commit_byte, "7340032");
CONF_Bool(enable_cloud_txn_lazy_commit, "true");
CONF_Int32(txn_lazy_commit_rowsets_thresold, "1000");
CONF_Int32(txn_lazy_commit_num_threads, "8");
+CONF_mBool(enable_cloud_parallel_txn_lazy_commit, "true");
+CONF_Int32(parallel_txn_lazy_commit_num_threads, "0"); // hardware concurrency if zero.
CONF_mInt64(txn_lazy_max_rowsets_per_batch, "1000");
+CONF_mBool(txn_lazy_commit_shuffle_partitions, "true");
+CONF_Int64(txn_lazy_commit_shuffle_seed, "0"); // 0 means generate a random seed
// max TabletIndexPB num for batch get
CONF_Int32(max_tablet_index_num_per_batch, "1000");
CONF_Int32(max_restore_job_rowsets_per_batch, "1000");
@@ -370,4 +383,37 @@ CONF_Int64(prune_aborted_snapshot_seconds, "3600"); // 1h
CONF_mString(aws_credentials_provider_version, "v2");
CONF_Validator(aws_credentials_provider_version,
[](const std::string& config) -> bool { return config == "v1" || config == "v2"; });
+
+// Snapshot configuration limits
+CONF_Int32(snapshot_min_interval_seconds, "3600"); // 1h min interval limit
+CONF_Int32(snapshot_max_reserved_num, "35"); // max reserved snapshots limit
+// New instance enable multi version status by default.
+// The new instance multi version status will be set to MULTI_VERSION_READ_WRITE.
+CONF_Bool(enable_multi_version_status, "false");
+// New instance enable cluster snapshot, it only works when enable_multi_version_status is true.
+// The new instance snapshot switch status will be set to SNAPSHOT_SWITCH_ON, and the auto snapshot will be open.
+CONF_Bool(enable_cluster_snapshot, "false");
+CONF_Bool(enable_snapshot_data_migrator, "false");
+CONF_Bool(enable_snapshot_chain_compactor, "false");
+CONF_Int32(snapshot_data_migrator_concurrent, "2");
+CONF_Int32(snapshot_chain_compactor_concurrent, "2");
+// Parallelism for snapshot migration and compaction operations
+//
+// When to adjust:
+// - Increase (to 20-50): Large-scale migrations (>10K tablets), sufficient resources
+// - Decrease (to 1-5): Memory/CPU constrained, high FDB conflict rate
+//
+// Cost of higher parallelism:
+// - Increases memory usage (transaction buffers, caches)
+// - Increases CPU usage (proportional to parallelism)
+// - Increases FDB load and may raise conflict rate
+CONF_Int32(snapshot_migrate_parallelism, "2");
+CONF_Int32(snapshot_compact_parallelism, "2");
+
+CONF_mBool(enable_notify_instance_update, "true");
+CONF_Bool(enable_instance_update_watcher, "true");
+
+CONF_mBool(advance_txn_lazy_commit_during_reads, "true");
+CONF_mBool(wait_txn_lazy_commit_during_reads, "true");
+
} // namespace doris::cloud::config
diff --git a/cloud/src/common/stopwatch.h b/cloud/src/common/stopwatch.h
index 4ac9abaa7f6..fa9fcfa7667 100644
--- a/cloud/src/common/stopwatch.h
+++ b/cloud/src/common/stopwatch.h
@@ -66,6 +66,10 @@ public:
.count();
}
+ int64_t elapsed_ms() const { return elapsed_us() / 1000; }
+
+ int64_t elapsed_seconds() const { return elapsed_ms() / 1000; }
+
private:
std::chrono::steady_clock::time_point start_;
std::chrono::steady_clock::duration elapsed_ {0};
diff --git a/cloud/src/recycler/sync_executor.h b/cloud/src/common/sync_executor.h
similarity index 100%
copy from cloud/src/recycler/sync_executor.h
copy to cloud/src/common/sync_executor.h
diff --git a/cloud/src/common/util.cpp b/cloud/src/common/util.cpp
index 7c3d8aeeff2..5cc942ea59f 100644
--- a/cloud/src/common/util.cpp
+++ b/cloud/src/common/util.cpp
@@ -208,9 +208,13 @@ std::string prettify_key(std::string_view key_hex, bool unicode) {
fields_pos.push_back(0);
for (auto& i : fields) {
- fields_str.emplace_back(std::get<1>(i) == EncodingTag::BYTES_TAG
- ? std::get<std::string>(std::get<0>(i))
- : std::to_string(std::get<int64_t>(std::get<0>(i))));
+ if (std::get<1>(i) == EncodingTag::BYTES_TAG) {
+ fields_str.emplace_back(std::get<std::string>(std::get<0>(i)));
+ } else if (std::get<1>(i) == EncodingTag::VERSIONSTAMP_TAG) {
+ fields_str.emplace_back("versionstamp: " + std::get<std::string>(std::get<0>(i)));
+ } else {
+ fields_str.emplace_back(std::to_string(std::get<int64_t>(std::get<0>(i))));
+ }
fields_pos.push_back((std::get<2>(i) + 1) * 2);
}
diff --git a/cloud/src/meta-service/http_encode_key.cpp b/cloud/src/meta-service/http_encode_key.cpp
index 4ee76af5c9f..800c6084c24 100644
--- a/cloud/src/meta-service/http_encode_key.cpp
+++ b/cloud/src/meta-service/http_encode_key.cpp
@@ -22,7 +22,6 @@
#include <google/protobuf/message.h>
#include <google/protobuf/util/json_util.h>
-#include <bit>
#include <chrono>
#include <fstream>
#include <iomanip>
@@ -34,7 +33,6 @@
#include <utility>
#include <vector>
-#include "common/config.h"
#include "common/logging.h"
#include "common/util.h"
#include "cpp/sync_point.h"
@@ -43,10 +41,11 @@
#include "meta-service/meta_service_schema.h"
#include "meta-service/meta_service_tablet_stats.h"
#include "meta-store/blob_message.h"
-#include "meta-store/codec.h"
+#include "meta-store/document_message.h"
#include "meta-store/keys.h"
#include "meta-store/txn_kv.h"
#include "meta-store/txn_kv_error.h"
+#include "meta-store/versioned_value.h"
namespace doris::cloud {
@@ -112,6 +111,13 @@ static std::string parse(const ValueBuf& buf) {
return proto_to_json(pb);
}
+template <class ProtoType>
+static std::string parse_to_json(const std::string& buf) {
+ ProtoType pb;
+ if (!pb.ParseFromString(buf)) return "";
+ return proto_to_json(pb);
+}
+
static std::string parse_txn_label(const ValueBuf& buf) {
std::string value;
if (buf.iters.size() != 1 || buf.iters[0]->size() != 1) {
@@ -199,6 +205,38 @@ static std::string parse_tablet_stats(const ValueBuf& buf) {
return json;
}
+static std::string parse_empty_value(const std::string& buf) {
+ return "";
+}
+
+static std::string parse_int64_value(const std::string& buf) {
+ if (buf.size() != sizeof(int64_t)) {
+ return "";
+ }
+ int64_t value = 0;
+ std::memcpy(&value, buf.data(), sizeof(int64_t));
+ return std::to_string(value);
+}
+
+// Helper function to parse versionstamp from URI query parameter
+static std::optional<Versionstamp> parse_versionstamp_from_uri(const brpc::URI& uri) {
+ std::string_view vs_str = http_query(uri, "versionstamp");
+ if (vs_str.empty()) {
+ return std::nullopt;
+ }
+
+ // versionstamp can be in hex format or direct bytes
+ std::string vs_bytes = unhex(vs_str);
+ if (vs_bytes.size() != 10) {
+ LOG(WARNING) << "Invalid versionstamp size: " << vs_bytes.size();
+ return std::nullopt;
+ }
+
+ std::array<uint8_t, 10> vs_array;
+ std::memcpy(vs_array.data(), vs_bytes.data(), 10);
+ return Versionstamp(vs_array);
+}
+
// See keys.h to get all types of key, e.g: MetaRowsetKeyInfo
// key_type -> {{param_name1, param_name2 ...}, key_encoding_func, serialized_pb_to_json_parsing_func, json_to_proto_parsing_func}
// where param names are the input for key_encoding_func
@@ -239,6 +277,34 @@ static std::unordered_map<std::string_view,
{"MetaServiceArnInfoKey", {std::vector<std::string_view> {}, [](param_type& p) { return system_meta_service_arn_info_key(); }, parse<RamUserPB> , parse_json<RamUserPB>}},
{"MetaServiceEncryptionKey", {std::vector<std::string_view> {}, [](param_type& p) { return system_meta_service_encryption_key_info_key(); }, parse<EncryptionKeyInfoPB> , parse_json<EncryptionKeyInfoPB>}},
};
+
+// Versioned key support (0x03 space)
+// key_type -> {{param_name1, param_name2 ...}, key_encoding_func, is_versioned_key, parse_func, json_to_proto_func}
+static std::unordered_map<std::string_view,
+ std::tuple<std::vector<std::string_view>,
+ std::function<std::string(param_type&)>,
+ bool,
+ std::function<std::string(const std::string&)>,
+ std::function<std::shared_ptr<google::protobuf::Message>(const std::string&)>>> versioned_param_set {
+ {"VersionedPartitionVersionKey", {{"instance_id", "partition_id"}, [](param_type& p) { return versioned::partition_version_key(KeyInfoSetter<versioned::PartitionVersionKeyInfo>{p}.get()); }, true, parse_to_json<VersionPB>, parse_json<VersionPB>}},
+ {"VersionedTableVersionKey", {{"instance_id", "table_id"}, [](param_type& p) { return versioned::table_version_key(KeyInfoSetter<versioned::TableVersionKeyInfo>{p}.get()); }, true, parse_empty_value, nullptr}},
+ {"VersionedPartitionIndexKey", {{"instance_id", "partition_id"}, [](param_type& p) { return versioned::partition_index_key(KeyInfoSetter<versioned::PartitionIndexKeyInfo>{p}.get()); }, false, parse_to_json<PartitionIndexPB>, parse_json<PartitionIndexPB>}},
+ {"VersionedPartitionInvertedIndexKey", {{"instance_id", "db_id", "table_id", "partition_id"}, [](param_type& p) { return versioned::partition_inverted_index_key(KeyInfoSetter<versioned::PartitionInvertedIndexKeyInfo>{p}.get()); }, false, parse_empty_value, nullptr}},
+ {"VersionedTabletIndexKey", {{"instance_id", "tablet_id"}, [](param_type& p) { return versioned::tablet_index_key(KeyInfoSetter<versioned::TabletIndexKeyInfo>{p}.get()); }, false, parse_to_json<TabletIndexPB>, parse_json<TabletIndexPB>}},
+ {"VersionedTabletInvertedIndexKey", {{"instance_id", "db_id", "table_id", "index_id", "partition_id", "tablet_id"}, [](param_type& p) { return versioned::tablet_inverted_index_key(KeyInfoSetter<versioned::TabletInvertedIndexKeyInfo>{p}.get()); }, false, parse_empty_value, nullptr}},
+ {"VersionedIndexIndexKey", {{"instance_id", "index_id"}, [](param_type& p) { return versioned::index_index_key(KeyInfoSetter<versioned::IndexIndexKeyInfo>{p}.get()); }, false, parse_to_json<IndexIndexPB>, parse_json<IndexIndexPB>}},
+ {"VersionedIndexInvertedKey", {{"instance_id", "db_id", "table_id", "index_id"}, [](param_type& p) { return versioned::index_inverted_key(KeyInfoSetter<versioned::IndexInvertedKeyInfo>{p}.get()); }, false, parse_empty_value, nullptr}},
+ {"VersionedTabletLoadStatsKey", {{"instance_id", "tablet_id"}, [](param_type& p) { return versioned::tablet_load_stats_key(KeyInfoSetter<versioned::TabletLoadStatsKeyInfo>{p}.get()); }, true, parse_to_json<TabletStatsPB>, parse_json<TabletStatsPB>}},
+ {"VersionedTabletCompactStatsKey", {{"instance_id", "tablet_id"}, [](param_type& p) { return versioned::tablet_compact_stats_key(KeyInfoSetter<versioned::TabletCompactStatsKeyInfo>{p}.get()); }, true, parse_to_json<TabletStatsPB>, parse_json<TabletStatsPB>}},
+ {"VersionedMetaPartitionKey", {{"instance_id", "partition_id"}, [](param_type& p) { return versioned::meta_partition_key(KeyInfoSetter<versioned::MetaPartitionKeyInfo>{p}.get()); }, true, parse_empty_value, nullptr}},
+ {"VersionedMetaIndexKey", {{"instance_id", "index_id"}, [](param_type& p) { return versioned::meta_index_key(KeyInfoSetter<versioned::MetaIndexKeyInfo>{p}.get()); }, true, parse_empty_value, nullptr}},
+ {"VersionedMetaTabletKey", {{"instance_id", "tablet_id"}, [](param_type& p) { return versioned::meta_tablet_key(KeyInfoSetter<versioned::MetaTabletKeyInfo>{p}.get()); }, true, parse_to_json<doris::TabletMetaCloudPB>, parse_json<doris::TabletMetaCloudPB>}},
+ {"VersionedMetaSchemaKey", {{"instance_id", "index_id", "schema_version"}, [](param_type& p) { return versioned::meta_schema_key(KeyInfoSetter<versioned::MetaSchemaKeyInfo>{p}.get()); }, false, parse_to_json<doris::TabletSchemaCloudPB>, parse_json<doris::TabletSchemaCloudPB>}},
+ {"VersionedMetaRowsetLoadKey", {{"instance_id", "tablet_id", "version"}, [](param_type& p) { return versioned::meta_rowset_load_key(KeyInfoSetter<versioned::MetaRowsetLoadKeyInfo>{p}.get()); }, true, [](const std::string& s) { return ""; }, parse_json<doris::RowsetMetaCloudPB>}},
+ {"VersionedMetaRowsetCompactKey", {{"instance_id", "tablet_id", "version"}, [](param_type& p) { return versioned::meta_rowset_compact_key(KeyInfoSetter<versioned::MetaRowsetCompactKeyInfo>{p}.get()); }, true, [](const std::string& s) { return ""; }, parse_json<doris::RowsetMetaCloudPB>}},
+ {"VersionedMetaDeleteBitmapKey", {{"instance_id", "tablet_id", "rowset_id"}, [](param_type& p) { return versioned::meta_delete_bitmap_key(KeyInfoSetter<versioned::MetaDeleteBitmapInfo>{p}.get()); }, false, parse_to_json<DeleteBitmapStoragePB>, parse_json<DeleteBitmapStoragePB>}},
+ {"VersionedDataRowsetRefCountKey", {{"instance_id", "tablet_id", "rowset_id"}, [](param_type& p) { return versioned::data_rowset_ref_count_key(KeyInfoSetter<versioned::DataRowsetRefCountKeyInfo>{p}.get()); }, false, parse_int64_value, nullptr}},
+};
// clang-format on
static MetaServiceResponseStatus encode_key(const brpc::URI& uri, std::string* key,
@@ -247,26 +313,49 @@ static MetaServiceResponseStatus encode_key(const brpc::URI& uri, std::string* k
status.set_code(MetaServiceCode::OK);
std::string_view kt = http_query(uri, "key_type");
if (key_type != nullptr) *key_type = kt;
+
+ // Try single version key first
auto it = param_set.find(kt);
- if (it == param_set.end()) {
- status.set_code(MetaServiceCode::INVALID_ARGUMENT);
- status.set_msg(fmt::format("key_type not supported: {}", (kt.empty() ? "(empty)" : kt)));
+ if (it != param_set.end()) {
+ auto& key_params = std::get<0>(it->second);
+ std::remove_cv_t<param_type> params;
+ params.reserve(key_params.size());
+ for (auto& i : key_params) {
+ auto p = uri.GetQuery(i.data());
+ if (p == nullptr || p->empty()) {
+ status.set_code(MetaServiceCode::INVALID_ARGUMENT);
+ status.set_msg(fmt::format("{} is not given or empty", i));
+ return status;
+ }
+ params.emplace_back(p);
+ }
+ auto& key_encoding_function = std::get<1>(it->second);
+ *key = key_encoding_function(params);
return status;
}
- auto& key_params = std::get<0>(it->second);
- std::remove_cv_t<param_type> params;
- params.reserve(key_params.size());
- for (auto& i : key_params) {
- auto p = uri.GetQuery(i.data());
- if (p == nullptr || p->empty()) {
- status.set_code(MetaServiceCode::INVALID_ARGUMENT);
- status.set_msg(fmt::format("{} is not given or empty", i));
- return status;
+
+ // Try versioned key
+ auto vit = versioned_param_set.find(kt);
+ if (vit != versioned_param_set.end()) {
+ auto& key_params = std::get<0>(vit->second);
+ std::remove_cv_t<param_type> params;
+ params.reserve(key_params.size());
+ for (auto& i : key_params) {
+ auto p = uri.GetQuery(i.data());
+ if (p == nullptr || p->empty()) {
+ status.set_code(MetaServiceCode::INVALID_ARGUMENT);
+ status.set_msg(fmt::format("{} is not given or empty", i));
+ return status;
+ }
+ params.emplace_back(p);
}
- params.emplace_back(p);
+ auto& key_encoding_function = std::get<1>(vit->second);
+ *key = key_encoding_function(params);
+ return status;
}
- auto& key_encoding_function = std::get<1>(it->second);
- *key = key_encoding_function(params);
+
+ status.set_code(MetaServiceCode::INVALID_ARGUMENT);
+ status.set_msg(fmt::format("key_type not supported: {}", (kt.empty() ? "(empty)" : kt)));
return status;
}
@@ -282,6 +371,7 @@ HttpResponse process_http_get_value(TxnKv* txn_kv, const brpc::URI& uri) {
return http_json_reply(st);
}
}
+
std::unique_ptr<Transaction> txn;
TxnErrorCode err = txn_kv->create_txn(&txn);
if (err != TxnErrorCode::TXN_OK) [[unlikely]] {
@@ -289,6 +379,75 @@ HttpResponse process_http_get_value(TxnKv* txn_kv, const brpc::URI& uri) {
fmt::format("failed to create txn, err={}", err));
}
+ // Check if it's a versioned key
+ auto vit = versioned_param_set.find(key_type);
+ if (vit != versioned_param_set.end()) {
+ bool is_versioned_key = std::get<2>(vit->second);
+ auto& parse_function = std::get<3>(vit->second);
+
+ // Get versionstamp parameter, default to Versionstamp::max() if not provided
+ Versionstamp snapshot_version = Versionstamp::max();
+ auto vs_opt = parse_versionstamp_from_uri(uri);
+ if (vs_opt.has_value()) {
+ snapshot_version = *vs_opt;
+ }
+
+ std::string value_json;
+ Versionstamp actual_version;
+ if (is_versioned_key) {
+ if (key_type == "VersionedMetaRowsetLoadKey" ||
+ key_type == "VersionedMetaRowsetCompactKey") {
+ doris::RowsetMetaCloudPB pb;
+ err = versioned::document_get(txn.get(), key, snapshot_version, &pb,
+ &actual_version, false);
+ if (err == TxnErrorCode::TXN_OK) {
+ value_json = proto_to_json(pb);
+ }
+ } else if (key_type == "VersionedMetaSchemaKey") {
+ doris::TabletSchemaCloudPB pb;
+ err = versioned::document_get(txn.get(), key, snapshot_version, &pb,
+ &actual_version, false);
+ if (err == TxnErrorCode::TXN_OK) {
+ value_json = proto_to_json(pb);
+ }
+ } else {
+ std::string value_str;
+ err = versioned_get(txn.get(), key, snapshot_version, &actual_version, &value_str,
+ false);
+ if (err == TxnErrorCode::TXN_OK) {
+ value_json = parse_function(value_str);
+ }
+ }
+ if (!value_json.empty()) {
+ value_json += fmt::format("\\nversionstamp={}", actual_version.to_string());
+ }
+ } else {
+ ValueBuf value_buf;
+ err = cloud::blob_get(txn.get(), key, &value_buf, true);
+ if (err == TxnErrorCode::TXN_OK) {
+ value_json = parse_function(value_buf.value());
+ }
+ }
+
+ if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ return http_json_reply(MetaServiceCode::KV_TXN_GET_ERR,
+ fmt::format("versioned key not found, key={}", hex(key)));
+ }
+ if (err != TxnErrorCode::TXN_OK) {
+ return http_json_reply(
+ MetaServiceCode::KV_TXN_GET_ERR,
+ fmt::format("failed to get versioned key, key={}, err={}", hex(key), err));
+ }
+ if (value_json.empty()) {
+ return http_json_reply(
+ MetaServiceCode::PROTOBUF_PARSE_ERR,
+ fmt::format("failed to parse versioned value, key={}", hex(key)));
+ }
+
+ return http_text_reply(MetaServiceCode::OK, "", value_json);
+ }
+
+ // Handle single version key (original logic)
auto it = param_set.find(key_type);
if (it == param_set.end()) {
return http_json_reply(MetaServiceCode::INVALID_ARGUMENT,
@@ -386,6 +545,93 @@ HttpResponse process_http_set_value(TxnKv* txn_kv, brpc::Controller* cntl) {
fmt::format("failed to create txn, err={}", err));
}
+ // Check if it's a versioned key
+ auto vit = versioned_param_set.find(key_type);
+ if (vit != versioned_param_set.end()) {
+ bool is_versioned_key = std::get<2>(vit->second);
+ auto& json_to_proto_function = std::get<4>(vit->second);
+
+ std::shared_ptr<google::protobuf::Message> pb_to_save;
+ if (json_to_proto_function) {
+ pb_to_save = json_to_proto_function(body);
+ }
+
+ // Check if versionstamp parameter is provided
+ auto vs_opt = parse_versionstamp_from_uri(uri);
+ if (is_versioned_key) {
+ if (key_type == "VersionedMetaRowsetLoadKey" ||
+ key_type == "VersionedMetaRowsetCompactKey" ||
+ key_type == "VersionedMetaSchemaKey") {
+ bool success = false;
+ if (vs_opt.has_value()) {
+ success = versioned::document_put(txn.get(), key, *vs_opt,
+ std::move(*pb_to_save));
+ } else {
+ success = versioned::document_put(txn.get(), key, std::move(*pb_to_save));
+ }
+ if (!success) {
+ return http_json_reply(
+ MetaServiceCode::UNDEFINED_ERR,
+ fmt::format("failed to put versioned document, key={}", hex(key)));
+ }
+ } else {
+ std::string value_to_save;
+ if (json_to_proto_function) {
+ value_to_save = pb_to_save->SerializeAsString();
+ if (value_to_save.empty()) {
+ return http_json_reply(
+ MetaServiceCode::UNDEFINED_ERR,
+ fmt::format("failed to serialize pb, key={}", hex(key)));
+ }
+ } else {
+ value_to_save = body;
+ }
+
+ // Put the value
+ if (vs_opt.has_value()) {
+ versioned_put(txn.get(), key, *vs_opt, value_to_save);
+ } else {
+ versioned_put(txn.get(), key, value_to_save);
+ }
+ }
+ } else {
+ std::string value_to_save;
+ if (key_type == "VersionedDataRowsetRefCountKey") {
+ // Parse int64 from body
+ try {
+ int64_t count = std::stoll(body);
+ value_to_save.resize(sizeof(int64_t));
+ std::memcpy(value_to_save.data(), &count, sizeof(int64_t));
+ } catch (...) {
+ return http_json_reply(MetaServiceCode::INVALID_ARGUMENT,
+ "failed to parse int64 value from body");
+ }
+ } else if (json_to_proto_function) {
+ value_to_save = pb_to_save->SerializeAsString();
+ if (value_to_save.empty()) {
+ return http_json_reply(MetaServiceCode::UNDEFINED_ERR,
+ fmt::format("failed to serialize pb, key={}", hex(key)));
+ }
+ } else {
+ value_to_save = body;
+ }
+ txn->put(key, value_to_save);
+ }
+
+ LOG(WARNING) << "set_value saved, key=" << hex(key);
+
+ err = txn->commit();
+ if (err != TxnErrorCode::TXN_OK) {
+ return http_json_reply(
+ MetaServiceCode::UNDEFINED_ERR,
+ fmt::format("failed to commit versioned key, key={}, err={}", hex(key), err));
+ }
+
+ LOG(WARNING) << "set_value saved versioned key, key=" << hex(key);
+ return http_text_reply(MetaServiceCode::OK, "",
+ fmt::format("versioned key saved successfully, key={}", hex(key)));
+ }
+
auto it = param_set.find(key_type);
if (it == param_set.end()) {
return http_json_reply(MetaServiceCode::INVALID_ARGUMENT,
@@ -479,6 +725,11 @@ HttpResponse process_http_encode_key(const brpc::URI& uri) {
return http_json_reply(st);
}
+ // Append versionstamp to key if versionstamp parameter is provided
+ if (auto vs_opt = parse_versionstamp_from_uri(uri); vs_opt.has_value()) {
+ key = encode_versioned_key(key, *vs_opt);
+ }
+
// Print to ensure
bool unicode = !(uri.GetQuery("unicode") != nullptr && *uri.GetQuery("unicode") == "false");
diff --git a/cloud/src/meta-service/meta_server.cpp b/cloud/src/meta-service/meta_server.cpp
index d8042342154..3e7f6cb0e64 100644
--- a/cloud/src/meta-service/meta_server.cpp
+++ b/cloud/src/meta-service/meta_server.cpp
@@ -28,9 +28,12 @@
#include <random>
#include <thread>
+#include "common/bvars.h"
#include "common/config.h"
+#include "common/defer.h"
#include "common/metric.h"
#include "common/network_util.h"
+#include "common/stopwatch.h"
#include "common/util.h"
#include "cpp/sync_point.h"
#include "meta-service/meta_service.h"
@@ -63,6 +66,17 @@ int MetaServer::start(brpc::Server* server) {
return -1;
}
+ // Add instance watcher
+ if (config::enable_instance_update_watcher) {
+ instance_watcher_.reset(new MetaServerInstanceWatcher(txn_kv_, rc_mgr));
+ ret = instance_watcher_->start();
+ TEST_SYNC_POINT_CALLBACK("MetaServer::start:3", &ret);
+ if (ret != 0) {
+ LOG(WARNING) << "failed to start instance watcher";
+ return -1;
+ }
+ }
+
auto rate_limiter = std::make_shared<RateLimiter>();
auto snapshot_mgr = std::make_shared<SnapshotManager>(txn_kv_);
@@ -85,6 +99,9 @@ int MetaServer::start(brpc::Server* server) {
void MetaServer::stop() {
server_register_->stop();
+ if (config::enable_instance_update_watcher) {
+ instance_watcher_->stop();
+ }
}
void MetaServerRegister::prepare_registry(ServiceRegistryPB* reg) {
@@ -196,4 +213,175 @@ void MetaServerRegister::stop() {
}
}
+MetaServerInstanceWatcher::~MetaServerInstanceWatcher() {
+ stop();
+}
+
+int MetaServerInstanceWatcher::start() {
+ if (txn_kv_ == nullptr) return -1;
+ std::unique_lock<std::mutex> lock(mtx_);
+ if (running_.load() != 0) {
+ LOG(INFO) << "instance watcher already started";
+ return -2;
+ }
+ running_.store(1);
+ instance_watch_thread_ = std::thread(&MetaServerInstanceWatcher::watch_instance_loop, this);
+ return 0;
+}
+
+void MetaServerInstanceWatcher::stop() {
+ {
+ std::unique_lock<std::mutex> lock(mtx_);
+ if (running_.load() == 2) {
+ LOG(INFO) << "instance watcher already stopped";
+ return;
+ }
+ running_.store(2);
+ cv_.notify_all();
+ }
+ if (instance_watch_thread_.joinable()) {
+ TxnErrorCode err = trigger_instance_watch();
+ if (err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to trigger instance watch when stopping instance watcher";
+ }
+ instance_watch_thread_.join();
+ }
+}
+
+void MetaServerInstanceWatcher::watch_instance_loop() {
+ pthread_setname_np(pthread_self(), "ms_instance_watcher");
+
+ LOG(INFO) << "instance watch thread begins to run";
+
+ constexpr int64_t MIN_SLEEP_INTERVAL_MS = 100; // 100 microsecond
+ constexpr int64_t MAX_SLEEP_INTERVAL_MS = 10000; // 10 second
+
+ std::string original_value;
+ std::unordered_map<std::string, std::string> instance_kvs_;
+
+ int64_t sleep_intervals_ms = MIN_SLEEP_INTERVAL_MS;
+ while (running_.load() == 1) {
+ TxnErrorCode err = watch_instance(instance_kvs_, original_value);
+ if (err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to watch instance, err=" << err;
+ std::unique_lock l(mtx_);
+ cv_.wait_for(l, std::chrono::milliseconds(sleep_intervals_ms));
+ sleep_intervals_ms = std::min(sleep_intervals_ms * 2, MAX_SLEEP_INTERVAL_MS);
+ continue;
+ }
+ sleep_intervals_ms = MIN_SLEEP_INTERVAL_MS;
+ }
+ LOG(INFO) << "instance watch thread quits";
+}
+
+TxnErrorCode MetaServerInstanceWatcher::watch_instance(
+ std::unordered_map<std::string, std::string>& instance_kvs_, std::string& original_value) {
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to create txn in watch_instance, err=" << err;
+ return err;
+ }
+
+ std::string key = system_meta_service_instance_update_key();
+ std::string new_value;
+ err = txn->get(key, &new_value);
+ if (err != TxnErrorCode::TXN_OK && err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ LOG(WARNING) << "failed to get instance update key in watch_instance, err=" << err;
+ return err;
+ } else if (err == TxnErrorCode::TXN_OK && new_value != original_value) {
+ LOG(INFO) << "instance update key changed, old_value=" << hex(original_value)
+ << " new_value=" << hex(new_value);
+ err = scan_and_notify_instance_updates(instance_kvs_);
+ if (err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to scan and notify instance updates in watch_instance, err="
+ << err;
+ return err;
+ }
+
+ // The instance update key is changed, update the original value, and continue to watch
+ original_value = new_value;
+ return TxnErrorCode::TXN_OK;
+ }
+
+ err = txn->watch_key(key);
+ if (err == TxnErrorCode::TXN_TOO_MANY_WATCHES) {
+ LOG(ERROR) << "too many watches registered in watch_instance, you may need to increase "
+ "the limitation";
+ return err;
+ } else if (err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to watch instance update key in watch_instance, err=" << err;
+ return err;
+ }
+
+ return TxnErrorCode::TXN_OK;
+}
+
+TxnErrorCode MetaServerInstanceWatcher::scan_and_notify_instance_updates(
+ std::unordered_map<std::string, std::string>& instance_kvs_) {
+ StopWatch sw;
+ DORIS_CLOUD_DEFER {
+ g_bvar_ms_scan_instance_update << sw.elapsed_us();
+ };
+
+ std::string begin_key = instance_key({""});
+ std::string end_key = instance_key({"\xff"}); // instance id are human readable strings
+
+ FullRangeGetOptions opts;
+ opts.txn_kv = txn_kv_;
+ opts.prefetch = true;
+ auto it = txn_kv_->full_range_get(begin_key, end_key, opts);
+
+ std::unordered_map<std::string, std::string> new_instance_kvs;
+ for (auto&& kvp = it->next(); kvp.has_value(); kvp = it->next()) {
+ std::string_view key = kvp->first;
+ std::string instance_id;
+ if (!decode_instance_key(&key, &instance_id)) {
+ LOG(WARNING) << "failed to decode instance key in watch_instance, key="
+ << hex(kvp->first);
+ return TxnErrorCode::TXN_INVALID_DATA;
+ }
+ new_instance_kvs.emplace(std::move(instance_id), kvp->second);
+ }
+ if (!it->is_valid()) {
+ return it->error_code();
+ }
+
+ for (auto&& [id, v] : new_instance_kvs) {
+ auto it = instance_kvs_.find(id);
+ if (it == instance_kvs_.end() || it->second != v) {
+ // New instance or updated instance info, notify resource manager to refresh
+ //
+ // The ResourceManager::refresh_instance() will new txn to get instance info,
+ // in order to avoid refreshing instance info with stale data.
+ auto&& [code, msg] = resource_manager_->refresh_instance(id);
+ if (code != MetaServiceCode::OK) {
+ LOG(WARNING) << "failed to refresh instance in watch_instance, instance_id=" << id
+ << " code=" << code << " msg=" << msg;
+ return TxnErrorCode::TXN_UNIDENTIFIED_ERROR;
+ }
+ }
+ }
+
+ instance_kvs_.swap(new_instance_kvs);
+
+ return TxnErrorCode::TXN_OK;
+}
+
+TxnErrorCode MetaServerInstanceWatcher::trigger_instance_watch() {
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to create txn to trigger instance watch";
+ return err;
+ }
+ txn->atomic_add(system_meta_service_instance_update_key(), 1);
+ err = txn->commit();
+ if (err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to commit txn to trigger instance watch";
+ return err;
+ }
+ return TxnErrorCode::TXN_OK;
+}
+
} // namespace doris::cloud
diff --git a/cloud/src/meta-service/meta_server.h b/cloud/src/meta-service/meta_server.h
index 15d4985d097..46764bdc285 100644
--- a/cloud/src/meta-service/meta_server.h
+++ b/cloud/src/meta-service/meta_server.h
@@ -29,7 +29,9 @@
namespace doris::cloud {
+class MetaServerInstanceWatcher;
class MetaServerRegister;
+class ResourceManager;
class MetaServer {
public:
@@ -48,6 +50,7 @@ public:
private:
std::shared_ptr<TxnKv> txn_kv_;
std::unique_ptr<MetaServerRegister> server_register_;
+ std::unique_ptr<MetaServerInstanceWatcher> instance_watcher_;
};
class ServiceRegistryPB;
@@ -92,4 +95,52 @@ private:
// first to destruct
};
+// Watches instance updates and notifies resource manager to refresh instance info
+class MetaServerInstanceWatcher {
+public:
+ MetaServerInstanceWatcher(std::shared_ptr<TxnKv> txn_kv,
+ std::shared_ptr<ResourceManager> resource_manager)
+ : running_(0),
+ resource_manager_(std::move(resource_manager)),
+ txn_kv_(std::move(txn_kv)) {}
+ ~MetaServerInstanceWatcher();
+
+ MetaServerInstanceWatcher(const MetaServerInstanceWatcher&) = delete;
+ MetaServerInstanceWatcher& operator=(const MetaServerInstanceWatcher&) = delete;
+
+ /**
+ * Starts watching instance updates
+ *
+ * @return 0 on success, otherwise failure.
+ */
+ int start();
+
+ /**
+ * Notifies all the threads to quit
+ */
+ void stop();
+
+private:
+ void watch_instance_loop();
+
+ TxnErrorCode watch_instance(std::unordered_map<std::string, std::string>& instance_kvs_,
+ std::string& original_value);
+
+ // Scans all instance info and notify resource manager to refresh instance info
+ // if there is any update.
+ TxnErrorCode scan_and_notify_instance_updates(
+ std::unordered_map<std::string, std::string>& instance_kvs_);
+
+ TxnErrorCode trigger_instance_watch();
+
+ std::thread instance_watch_thread_;
+ std::atomic<int> running_;
+ std::mutex mtx_;
+ std::condition_variable cv_;
+
+ std::shared_ptr<ResourceManager> resource_manager_;
+ std::shared_ptr<TxnKv> txn_kv_; // Relies on other members, must be the
+ // first to destruct
+};
+
} // namespace doris::cloud
diff --git a/cloud/src/meta-service/meta_service.cpp b/cloud/src/meta-service/meta_service.cpp
index 10b0102fb8e..9a4533288f0 100644
--- a/cloud/src/meta-service/meta_service.cpp
+++ b/cloud/src/meta-service/meta_service.cpp
@@ -64,14 +64,15 @@
#include "meta-service/meta_service_schema.h"
#include "meta-service/meta_service_tablet_stats.h"
#include "meta-store/blob_message.h"
+#include "meta-store/clone_chain_reader.h"
#include "meta-store/codec.h"
#include "meta-store/document_message.h"
#include "meta-store/keys.h"
-#include "meta-store/meta_reader.h"
#include "meta-store/txn_kv.h"
#include "meta-store/txn_kv_error.h"
#include "meta-store/versioned_value.h"
#include "rate-limiter/rate_limiter.h"
+#include "resource-manager/resource_manager.h"
using namespace std::chrono;
@@ -84,7 +85,7 @@ MetaServiceImpl::MetaServiceImpl(std::shared_ptr<TxnKv> txn_kv,
: txn_kv_(std::move(txn_kv)),
resource_mgr_(std::move(resource_mgr)),
rate_limiter_(std::move(rate_limiter)),
- txn_lazy_committer_(std::make_shared<TxnLazyCommitter>(txn_kv_)),
+ txn_lazy_committer_(std::make_shared<TxnLazyCommitter>(txn_kv_, resource_mgr_)),
delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
snapshot_manager_(std::move(snapshot_manager)) {
rate_limiter_->init(this);
@@ -260,7 +261,7 @@ void MetaServiceImpl::get_version(::google::protobuf::RpcController* controller,
bool is_versioned_read = is_version_read_enabled(instance_id);
if (is_versioned_read) {
- MetaReader reader(instance_id, txn_kv_.get());
+ CloneChainReader reader(instance_id, txn_kv_.get(), resource_mgr_.get());
if (is_table_version) {
Versionstamp table_version;
TxnErrorCode err = reader.get_table_version(table_id, &table_version);
@@ -288,6 +289,24 @@ void MetaServiceImpl::get_version(::google::protobuf::RpcController* controller,
table_id);
return;
}
+
+ if (request->wait_for_pending_txn() && partition_version.pending_txn_ids_size() > 0) {
+ DCHECK_EQ(partition_version.pending_txn_ids_size(), 1)
+ << "only support one pending txn id for now, version="
+ << partition_version.ShortDebugString();
+ int64_t first_txn_id = partition_version.pending_txn_ids(0);
+ std::shared_ptr<TxnLazyCommitTask> task =
+ txn_lazy_committer_->submit(instance_id, first_txn_id);
+ std::tie(code, msg) = task->wait();
+ if (code != MetaServiceCode::OK) {
+ LOG(WARNING) << "wait for pending txn " << first_txn_id
+ << " failed, code=" << code << " msg=" << msg;
+ return;
+ }
+ partition_version.set_version(partition_version.version() + 1);
+ partition_version.clear_pending_txn_ids();
+ }
+
response->set_version(partition_version.version());
response->add_version_update_time_ms(partition_version.update_time_ms());
}
@@ -337,6 +356,23 @@ void MetaServiceImpl::get_version(::google::protobuf::RpcController* controller,
return;
}
+ if (request->wait_for_pending_txn() && version_pb.pending_txn_ids_size() > 0) {
+ DCHECK_EQ(version_pb.pending_txn_ids_size(), 1)
+ << "only support one pending txn id for now, version="
+ << version_pb.ShortDebugString();
+ int64_t first_txn_id = version_pb.pending_txn_ids(0);
+ std::shared_ptr<TxnLazyCommitTask> task =
+ txn_lazy_committer_->submit(instance_id, first_txn_id);
+ std::tie(code, msg) = task->wait();
+ if (code != MetaServiceCode::OK) {
+ LOG(WARNING) << "wait for pending txn " << first_txn_id
+ << " failed, code=" << code << " msg=" << msg;
+ return;
+ }
+ version_pb.set_version(version_pb.version() + 1);
+ version_pb.clear_pending_txn_ids();
+ }
+
response->set_version(version_pb.version());
response->add_version_update_time_ms(version_pb.update_time_ms());
}
@@ -464,36 +500,49 @@ void MetaServiceImpl::batch_get_version(::google::protobuf::RpcController* contr
break;
}
- for (auto&& value : version_values) {
- if (!value.has_value()) {
- // return -1 if the target version is not exists.
- response->add_versions(-1);
- response->add_version_update_time_ms(-1);
- } else if (is_table_version) {
- int64_t version = 0;
- if (!txn->decode_atomic_int(*value, &version)) {
- code = MetaServiceCode::PROTOBUF_PARSE_ERR;
- msg = "malformed table version value";
- break;
+ if (is_table_version) {
+ for (auto&& value : version_values) {
+ if (!value.has_value()) {
+ // return -1 if the target version is not exists.
+ response->add_versions(-1);
+ } else {
+ int64_t version = 0;
+ if (!txn->decode_atomic_int(*value, &version)) {
+ code = MetaServiceCode::PROTOBUF_PARSE_ERR;
+ msg = "malformed table version value";
+ break;
+ }
+ response->add_versions(version);
}
- response->add_versions(version);
- } else {
+ }
+ } else {
+ std::vector<VersionPB> partition_versions;
+ for (auto&& value : version_values) {
VersionPB version_pb;
- if (!version_pb.ParseFromString(*value)) {
+ if (!value.has_value()) {
+ // return -1 if the target version is not exists.
+ version_pb.set_version(-1);
+ version_pb.set_update_time_ms(-1);
+ } else if (!version_pb.ParseFromString(*value)) {
code = MetaServiceCode::PROTOBUF_PARSE_ERR;
msg = "malformed version value";
break;
}
-
- if (!version_pb.has_version()) {
- // return -1 if the target version is not exists.
- response->add_versions(-1);
- response->add_version_update_time_ms(-1);
- } else {
- response->add_versions(version_pb.version());
- response->add_version_update_time_ms(version_pb.update_time_ms());
+ partition_versions.push_back(std::move(version_pb));
+ }
+ if (code != MetaServiceCode::OK) {
+ break;
+ }
+ if (request->wait_for_pending_txn()) {
+ std::tie(code, msg) = wait_for_pending_txns(instance_id, partition_versions);
+ if (code != MetaServiceCode::OK) {
+ break;
}
}
+ for (auto& version_pb : partition_versions) {
+ response->add_versions(version_pb.version());
+ response->add_version_update_time_ms(version_pb.update_time_ms());
+ }
}
}
}
@@ -514,7 +563,7 @@ std::pair<MetaServiceCode, std::string> MetaServiceImpl::batch_get_table_version
response->mutable_partition_ids()->CopyFrom(request->partition_ids());
constexpr size_t BATCH_SIZE = 500;
- MetaReader reader(instance_id, txn_kv_.get());
+ CloneChainReader reader(instance_id, txn_kv_.get(), resource_mgr_.get());
std::vector<int64_t> acquired_ids;
acquired_ids.reserve(BATCH_SIZE);
@@ -573,7 +622,7 @@ std::pair<MetaServiceCode, std::string> MetaServiceImpl::batch_get_partition_ver
constexpr size_t BATCH_SIZE = 500;
- MetaReader reader(instance_id, txn_kv_.get());
+ CloneChainReader reader(instance_id, txn_kv_.get(), resource_mgr_.get());
std::vector<int64_t> acquired_ids;
acquired_ids.reserve(BATCH_SIZE);
@@ -594,10 +643,10 @@ std::pair<MetaServiceCode, std::string> MetaServiceImpl::batch_get_partition_ver
for (size_t j = i; j < limit; j++) {
acquired_ids.push_back(request->partition_ids(j));
}
- std::unordered_map<int64_t, VersionPB> partition_versions;
+ std::unordered_map<int64_t, VersionPB> partition_version_map;
std::unordered_map<int64_t, Versionstamp> versionstamps;
- err = reader.get_partition_versions(acquired_ids, &partition_versions, &versionstamps,
- true);
+ err = reader.get_partition_versions(acquired_ids, &partition_version_map,
+ &versionstamps, true);
if (err == TxnErrorCode::TXN_TOO_OLD) {
// txn too old, fallback to non-snapshot versions.
LOG(WARNING) << "batch_get_version execution time exceeds the txn mvcc window, "
@@ -608,17 +657,31 @@ std::pair<MetaServiceCode, std::string> MetaServiceImpl::batch_get_partition_ver
return {cast_as<ErrCategory::READ>(err),
fmt::format("failed to batch get versions, index={}, err={}", i, err)};
}
+
+ std::vector<VersionPB> partition_versions;
for (auto& acquired_id : acquired_ids) {
- auto it = partition_versions.find(acquired_id);
- if (it == partition_versions.end()) {
+ auto it = partition_version_map.find(acquired_id);
+ if (it == partition_version_map.end()) {
// return -1 if the target version is not exists.
- response->add_versions(-1);
- response->add_version_update_time_ms(-1);
+ VersionPB version_pb;
+ version_pb.set_version(-1);
+ version_pb.set_update_time_ms(-1);
+ partition_versions.push_back(std::move(version_pb));
} else {
- response->add_versions(it->second.version());
- response->add_version_update_time_ms(it->second.update_time_ms());
+ partition_versions.push_back(it->second);
}
}
+ if (request->wait_for_pending_txn()) {
+ auto&& [code, msg] =
+ wait_for_pending_txns(std::string(instance_id), partition_versions);
+ if (code != MetaServiceCode::OK) {
+ return {code, msg};
+ }
+ }
+ for (auto& version_pb : partition_versions) {
+ response->add_versions(version_pb.version());
+ response->add_version_update_time_ms(version_pb.update_time_ms());
+ }
}
}
@@ -680,6 +743,13 @@ void internal_create_tablet(const CreateTabletsRequest* request, MetaServiceCode
}
txn->put(rs_key, rs_val);
if (is_versioned_write) {
+ std::string meta_rowset_key = versioned::meta_rowset_key(
+ {instance_id, tablet_id, first_rowset->rowset_id_v2()});
+ blob_put(txn.get(), meta_rowset_key, rs_val, 0);
+
+ std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
+ {instance_id, tablet_id, first_rowset->rowset_id_v2()});
+ txn->atomic_add(rowset_ref_count_key, 1);
std::string versioned_rs_key = versioned::meta_rowset_load_key(
{instance_id, tablet_id, first_rowset->end_version()});
if (!versioned::document_put(txn.get(), versioned_rs_key, std::move(*first_rowset))) {
@@ -689,8 +759,11 @@ void internal_create_tablet(const CreateTabletsRequest* request, MetaServiceCode
return;
}
LOG(INFO) << "put first versioned rowset meta, tablet_id=" << tablet_id
+ << " rowset_id=" << first_rowset->rowset_id_v2()
<< " end_version=" << first_rowset->end_version()
- << " key=" << hex(versioned_rs_key);
+ << " key=" << hex(versioned_rs_key)
+ << " rowset_ref_count_key=" << hex(rowset_ref_count_key)
+ << " meta_rowset_key=" << hex(meta_rowset_key);
}
tablet_meta.clear_rs_metas(); // Strip off rowset meta
@@ -798,7 +871,12 @@ void internal_create_tablet(const CreateTabletsRequest* request, MetaServiceCode
}
txn->put(key1, val1);
LOG(INFO) << "put tablet_idx tablet_id=" << tablet_id << " key=" << hex(key1);
- if (request->has_db_id() && is_versioned_write) {
+ if (is_versioned_write) {
+ if (!request->has_db_id()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "db_id is required for versioned write, please upgrade your FE version";
+ return;
+ }
int64_t db_id = request->db_id();
std::string tablet_idx_key = versioned::tablet_index_key({instance_id, tablet_id});
std::string tablet_inverted_idx_key = versioned::tablet_inverted_index_key(
@@ -834,19 +912,6 @@ void internal_create_tablet(const CreateTabletsRequest* request, MetaServiceCode
<< " index_id=" << index_id << " partition_id=" << partition_id
<< " key=" << hex(stats_key);
if (is_versioned_write) {
- std::string load_stats_key = versioned::tablet_load_stats_key({instance_id, tablet_id});
- TabletStatsPB stats_pb_copy(stats_pb);
- if (!versioned::document_put(txn.get(), load_stats_key, std::move(stats_pb_copy))) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- msg = fmt::format("failed to serialize versioned tablet stats, key={}",
- hex(load_stats_key));
- return;
- }
-
- // The compact stats is initialized with zero values
- stats_pb.set_num_rows(0);
- stats_pb.set_num_rowsets(0);
- stats_pb.set_num_segments(0);
std::string compact_stats_key =
versioned::tablet_compact_stats_key({instance_id, tablet_id});
if (!versioned::document_put(txn.get(), compact_stats_key, std::move(stats_pb))) {
@@ -855,6 +920,17 @@ void internal_create_tablet(const CreateTabletsRequest* request, MetaServiceCode
hex(compact_stats_key));
return;
}
+
+ // The load stats is initialized with zero values
+ TabletStatsPB empty_stats_pb;
+ std::string load_stats_key = versioned::tablet_load_stats_key({instance_id, tablet_id});
+ if (!versioned::document_put(txn.get(), load_stats_key, std::move(empty_stats_pb))) {
+ code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
+ msg = fmt::format("failed to serialize versioned tablet stats, key={}",
+ hex(load_stats_key));
+ return;
+ }
+
LOG(INFO) << "put versioned tablet load and compact stats, tablet_id=" << tablet_id
<< " load_stats_key=" << hex(load_stats_key)
<< " compact_stats_key=" << hex(compact_stats_key);
@@ -886,6 +962,7 @@ void MetaServiceImpl::create_tablets(::google::protobuf::RpcController* controll
LOG(INFO) << msg << ", cloud_unique_id=" << request->cloud_unique_id();
return;
}
+
RPC_RATE_LIMIT(create_tablets)
for (; request->has_storage_vault_name();) {
InstanceInfoPB instance;
@@ -1029,7 +1106,8 @@ void internal_get_tablet(MetaServiceCode& code, std::string& msg, const std::str
static bool try_fetch_and_parse_schema(Transaction* txn, TabletSchemaCloudPB* schema,
const std::string& instance_id, int64_t index_id,
int64_t schema_version, MetaServiceCode& code,
- std::string& msg, bool is_versioned_read) {
+ std::string& msg, bool is_versioned_read,
+ ResourceManager* resource_mgr) {
if (!is_versioned_read) {
std::string key = meta_schema_key({instance_id, index_id, schema_version});
ValueBuf val_buf;
@@ -1045,7 +1123,7 @@ static bool try_fetch_and_parse_schema(Transaction* txn, TabletSchemaCloudPB* sc
return false;
}
} else {
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr);
TxnErrorCode err = reader.get_tablet_schema(txn, index_id, schema_version, schema);
if (err != TxnErrorCode::TXN_OK) {
code = cast_as<ErrCategory::READ>(err);
@@ -1079,7 +1157,7 @@ void MetaServiceImpl::update_tablet(::google::protobuf::RpcController* controlle
UpdateTabletLogPB update_tablet_log;
bool is_versioned_write = is_version_write_enabled(instance_id);
bool is_versioned_read = is_version_read_enabled(instance_id);
- MetaReader reader(instance_id, txn_kv_.get());
+ CloneChainReader reader(instance_id, txn_kv_.get(), resource_mgr_.get());
for (const TabletMetaInfoPB& tablet_meta_info : request->tablet_meta_infos()) {
doris::TabletMetaCloudPB tablet_meta;
if (!is_versioned_read) {
@@ -1126,9 +1204,10 @@ void MetaServiceImpl::update_tablet(::google::protobuf::RpcController* controlle
tablet_meta_info.disable_auto_compaction());
} else {
doris::TabletSchemaCloudPB schema_pb;
- if (!try_fetch_and_parse_schema(
- txn.get(), &schema_pb, instance_id, tablet_meta.index_id(),
- tablet_meta.schema_version(), code, msg, is_versioned_read)) {
+ if (!try_fetch_and_parse_schema(txn.get(), &schema_pb, instance_id,
+ tablet_meta.index_id(),
+ tablet_meta.schema_version(), code, msg,
+ is_versioned_read, resource_mgr_.get())) {
return;
}
@@ -1181,16 +1260,10 @@ void MetaServiceImpl::update_tablet(::google::protobuf::RpcController* controlle
if (is_versioned_write && update_tablet_log.tablet_ids_size() > 0) {
OperationLogPB log;
log.mutable_update_tablet()->Swap(&update_tablet_log);
- std::string update_log_key = versioned::log_key(instance_id);
- std::string operation_log_value;
- if (!log.SerializeToString(&operation_log_value)) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- msg = "failed to serialize update tablet log";
- return;
- }
- versioned_put(txn.get(), update_log_key, operation_log_value);
- LOG(INFO) << "put versioned update tablet log, key=" << hex(update_log_key)
- << " instance_id=" << instance_id << " log_size=" << operation_log_value.size();
+ std::string log_key = versioned::log_key(instance_id);
+ versioned::blob_put(txn.get(), log_key, log);
+ LOG(INFO) << "put update tablet operation log, key=" << hex(log_key)
+ << " instance_id=" << instance_id;
}
err = txn->commit();
@@ -1227,7 +1300,7 @@ void MetaServiceImpl::get_tablet(::google::protobuf::RpcController* controller,
return;
}
- MetaReader reader(instance_id, txn_kv_.get());
+ CloneChainReader reader(instance_id, resource_mgr_.get());
TabletMetaCloudPB tablet_meta;
err = reader.get_tablet_meta(txn.get(), request->tablet_id(), &tablet_meta, nullptr);
if (err != TxnErrorCode::TXN_OK) {
@@ -1264,7 +1337,7 @@ static void set_schema_in_existed_rowset(MetaServiceCode& code, std::string& msg
const std::string& instance_id,
doris::RowsetMetaCloudPB& rowset_meta,
doris::RowsetMetaCloudPB& existed_rowset_meta,
- bool is_versioned_read) {
+ bool is_versioned_read, ResourceManager* resource_mgr) {
DCHECK(existed_rowset_meta.has_index_id());
if (!existed_rowset_meta.has_schema_version()) {
code = MetaServiceCode::INVALID_ARGUMENT;
@@ -1288,7 +1361,7 @@ static void set_schema_in_existed_rowset(MetaServiceCode& code, std::string& msg
if (!try_fetch_and_parse_schema(txn, existed_rowset_meta.mutable_tablet_schema(),
instance_id, existed_rowset_meta.index_id(),
existed_rowset_meta.schema_version(), code, msg,
- is_versioned_read)) {
+ is_versioned_read, resource_mgr)) {
return;
}
}
@@ -1726,6 +1799,24 @@ void MetaServiceImpl::commit_restore_job(::google::protobuf::RpcController* cont
.tag("rowset_size", rs_key.size() + rs_val.size())
.tag("rowset_meta", rowset_meta.DebugString());
+ if (is_versioned_write) {
+ std::string meta_rowset_load_key = versioned::meta_rowset_load_key(
+ {instance_id, tablet_idx.tablet_id(), rowset_meta.end_version()});
+ // Put versioned rowset compact metadata for new tablet's rowsets
+ LOG_INFO("put restore job's versioned meta rowset load key")
+ .tag("instance_id", instance_id)
+ .tag("meta_rowset_load_key", hex(meta_rowset_load_key))
+ .tag("tablet_id", tablet_idx.tablet_id());
+ // if will revert in drop_partition rpc if commit restore_job failed
+ if (!versioned::document_put(txn.get(), meta_rowset_load_key,
+ std::move(rowset_meta))) {
+ code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
+ msg = fmt::format("failed to serialize versioned rowset meta, key={}",
+ hex(meta_rowset_load_key));
+ return;
+ }
+ }
+
tablet_stat.data_size += rowset_meta.total_disk_size();
tablet_stat.num_rows += rowset_meta.num_rows();
tablet_stat.num_segs += rowset_meta.num_segments();
@@ -1969,6 +2060,21 @@ void MetaServiceImpl::commit_restore_job(::google::protobuf::RpcController* cont
.tag("tablet_id", tablet_idx.tablet_id())
.tag("tablet_size", tablet_key.size() + tablet_val.size());
+ if (is_versioned_write) {
+ std::string versioned_tablet_key =
+ versioned::meta_tablet_key({instance_id, tablet_meta->tablet_id()});
+ TabletMetaCloudPB meta;
+ meta.CopyFrom(*tablet_meta);
+ if (!versioned::document_put(txn0.get(), versioned_tablet_key, std::move(meta))) {
+ code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
+ msg = fmt::format("failed to serialize versioned tablet meta, key={}",
+ hex(versioned_tablet_key));
+ return;
+ }
+ LOG(INFO) << "put versioned tablet meta, tablet_id=" << tablet_meta->tablet_id()
+ << " key=" << hex(versioned_tablet_key);
+ }
+
StatsTabletKeyInfo stat_info {instance_id, tablet_meta->table_id(), tablet_meta->index_id(),
tablet_meta->partition_id(), tablet_meta->tablet_id()};
std::string stats_key;
@@ -1988,6 +2094,30 @@ void MetaServiceImpl::commit_restore_job(::google::protobuf::RpcController* cont
.tag("tablet_id", tablet_meta->tablet_id())
.tag("stats key", hex(stats_key));
+ if (is_versioned_write) {
+ TabletStatsPB tablet_load_stats;
+ auto tablet_load_stats_val = tablet_load_stats.SerializeAsString();
+ std::string tablet_load_stats_version_key =
+ versioned::tablet_load_stats_key({instance_id, tablet_meta->tablet_id()});
+ LOG_INFO("put versioned tablet load stats key")
+ .tag("tablet_load_stats_version_key", hex(tablet_load_stats_version_key))
+ .tag("tablet_id", tablet_meta->tablet_id())
+ .tag("value_size", tablet_load_stats_val.size())
+ .tag("instance_id", instance_id);
+ versioned_put(txn0.get(), tablet_load_stats_version_key, tablet_load_stats_val);
+
+ TabletStatsPB tablet_compact_stats;
+ tablet_compact_stats.CopyFrom(stats_pb);
+ auto tablet_compact_stats_val = tablet_compact_stats.SerializeAsString();
+ std::string tablet_compact_stats_version_key =
+ versioned::tablet_compact_stats_key({instance_id, tablet_meta->tablet_id()});
+ LOG_INFO("put versioned tablet compact stats key")
+ .tag("tablet_compact_stats_version_key", hex(tablet_compact_stats_version_key))
+ .tag("tablet_id", tablet_meta->tablet_id())
+ .tag("value_size", tablet_compact_stats_val.size())
+ .tag("instance_id", instance_id);
+ versioned_put(txn0.get(), tablet_compact_stats_version_key, tablet_compact_stats_val);
+ }
update_tablet_stats(stat_info, tablet_stat, txn0, code, msg);
if (code != MetaServiceCode::OK) {
return;
@@ -2172,7 +2302,7 @@ static void fill_schema_from_dict(MetaServiceCode& code, std::string& msg,
bool check_job_existed(Transaction* txn, MetaServiceCode& code, std::string& msg,
const std::string& instance_id, int64_t tablet_id,
const std::string& rowset_id, const std::string& job_id,
- bool is_versioned_read) {
+ bool is_versioned_read, ResourceManager* resource_mgr) {
TabletIndexPB tablet_idx;
if (!is_versioned_read) {
get_tablet_idx(code, msg, txn, instance_id, tablet_id, tablet_idx);
@@ -2180,7 +2310,7 @@ bool check_job_existed(Transaction* txn, MetaServiceCode& code, std::string& msg
return false;
}
} else {
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr);
TxnErrorCode err = reader.get_tablet_index(txn, tablet_id, &tablet_idx);
if (err != TxnErrorCode::TXN_OK) {
code = cast_as<ErrCategory::READ>(err);
@@ -2348,7 +2478,7 @@ void MetaServiceImpl::prepare_rowset(::google::protobuf::RpcController* controll
if (config::enable_tablet_job_check && request->has_tablet_job_id() &&
!request->tablet_job_id().empty()) {
if (!check_job_existed(txn.get(), code, msg, instance_id, tablet_id, rowset_id,
- request->tablet_job_id(), is_versioned_read)) {
+ request->tablet_job_id(), is_versioned_read, resource_mgr_.get())) {
return;
}
}
@@ -2387,7 +2517,7 @@ void MetaServiceImpl::prepare_rowset(::google::protobuf::RpcController* controll
existed_rowset_meta->set_index_id(tablet_idx.index_id());
rowset_meta.set_index_id(tablet_idx.index_id());
} else {
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr_.get());
TabletIndexPB tablet_idx;
TxnErrorCode err = reader.get_tablet_index(txn.get(), tablet_id, &tablet_idx);
if (err != TxnErrorCode::TXN_OK) {
@@ -2405,7 +2535,8 @@ void MetaServiceImpl::prepare_rowset(::google::protobuf::RpcController* controll
}
if (!existed_rowset_meta->has_tablet_schema()) {
set_schema_in_existed_rowset(code, msg, txn.get(), instance_id, rowset_meta,
- *existed_rowset_meta, is_versioned_read);
+ *existed_rowset_meta, is_versioned_read,
+ resource_mgr_.get());
if (code != MetaServiceCode::OK) return;
} else {
existed_rowset_meta->set_schema_version(
@@ -2509,7 +2640,7 @@ void MetaServiceImpl::commit_rowset(::google::protobuf::RpcController* controlle
if (config::enable_tablet_job_check && request->has_tablet_job_id() &&
!request->tablet_job_id().empty()) {
if (!check_job_existed(txn.get(), code, msg, instance_id, tablet_id, rowset_id,
- request->tablet_job_id(), is_versioned_read)) {
+ request->tablet_job_id(), is_versioned_read, resource_mgr_.get())) {
return;
}
}
@@ -2553,7 +2684,7 @@ void MetaServiceImpl::commit_rowset(::google::protobuf::RpcController* controlle
if (code != MetaServiceCode::OK) return;
existed_rowset_meta->set_index_id(tablet_idx.index_id());
} else {
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr_.get());
TabletIndexPB tablet_idx;
TxnErrorCode err = reader.get_tablet_index(txn.get(), tablet_id, &tablet_idx);
if (err != TxnErrorCode::TXN_OK) {
@@ -2570,7 +2701,8 @@ void MetaServiceImpl::commit_rowset(::google::protobuf::RpcController* controlle
}
if (!existed_rowset_meta->has_tablet_schema()) {
set_schema_in_existed_rowset(code, msg, txn.get(), instance_id, rowset_meta,
- *existed_rowset_meta, is_versioned_read);
+ *existed_rowset_meta, is_versioned_read,
+ resource_mgr_.get());
if (code != MetaServiceCode::OK) return;
} else {
existed_rowset_meta->set_schema_version(
@@ -2597,7 +2729,7 @@ void MetaServiceImpl::commit_rowset(::google::protobuf::RpcController* controlle
if (code != MetaServiceCode::OK) return;
rowset_meta.set_index_id(tablet_idx.index_id());
} else if (!rowset_meta.has_index_id()) {
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr_.get());
TabletIndexPB tablet_idx;
TxnErrorCode err =
reader.get_tablet_index(txn.get(), rowset_meta.tablet_id(), &tablet_idx);
@@ -2633,20 +2765,38 @@ void MetaServiceImpl::commit_rowset(::google::protobuf::RpcController* controlle
rowset_meta.set_allocated_tablet_schema(nullptr);
}
+ auto recycle_rs_key = recycle_rowset_key({instance_id, tablet_id, rowset_id});
+ txn->remove(recycle_rs_key);
+
+ DCHECK_GT(rowset_meta.txn_expiration(), 0);
+ auto tmp_rs_val = rowset_meta.SerializeAsString();
+ txn->put(tmp_rs_key, tmp_rs_val);
+
if (is_version_write_enabled(instance_id)) {
std::string rowset_ref_count_key =
versioned::data_rowset_ref_count_key({instance_id, tablet_id, rowset_id});
LOG(INFO) << "add rowset ref count key, instance_id=" << instance_id
<< "key=" << hex(rowset_ref_count_key);
txn->atomic_add(rowset_ref_count_key, 1);
- }
- auto recycle_rs_key = recycle_rowset_key({instance_id, tablet_id, rowset_id});
- txn->remove(recycle_rs_key);
+ // Recycler uses end_version to check if the meta_rowset_compact_key or
+ // meta_rowset_load_key exists.
+ // The end_version is not set if rowset is committed by load, later commit_txn will write
+ // this key again to save end_version.
+ std::string meta_rowset_key =
+ versioned::meta_rowset_key({instance_id, tablet_id, rowset_id});
+ if (config::enable_recycle_rowset_strip_key_bounds) {
+ doris::RowsetMetaCloudPB rowset_meta_copy = rowset_meta;
+ // Strip key bounds to shrink operation log for ts compaction recycle entries
+ rowset_meta_copy.clear_segments_key_bounds();
+ rowset_meta_copy.clear_segments_key_bounds_truncated();
+ blob_put(txn.get(), meta_rowset_key, rowset_meta_copy.SerializeAsString(), 0);
+ } else {
+ blob_put(txn.get(), meta_rowset_key, tmp_rs_val, 0);
+ }
+ LOG(INFO) << "put versioned meta_rowset_key=" << hex(meta_rowset_key);
+ }
- DCHECK_GT(rowset_meta.txn_expiration(), 0);
- auto tmp_rs_val = rowset_meta.SerializeAsString();
- txn->put(tmp_rs_key, tmp_rs_val);
std::size_t segment_key_bounds_bytes = get_segments_key_bounds_bytes(rowset_meta);
LOG(INFO) << "put tmp_rs_key " << hex(tmp_rs_key) << " delete recycle_rs_key "
<< hex(recycle_rs_key) << " value_size " << tmp_rs_val.size() << " txn_id "
@@ -2994,7 +3144,7 @@ void MetaServiceImpl::get_rowset(::google::protobuf::RpcController* controller,
int64_t req_cp = request->cumulative_point();
bool is_versioned_read = is_version_read_enabled(instance_id);
- MetaReader reader(instance_id, txn_kv_.get());
+ CloneChainReader reader(instance_id, txn_kv_.get(), resource_mgr_.get());
do {
TEST_SYNC_POINT_CALLBACK("get_rowset:begin", &tablet_id);
std::unique_ptr<Transaction> txn;
@@ -3029,7 +3179,7 @@ void MetaServiceImpl::get_rowset(::google::protobuf::RpcController* controller,
}
DCHECK(request->has_idx());
- if (idx.has_db_id()) {
+ if (idx.has_db_id() && config::advance_txn_lazy_commit_during_reads) {
// there is maybe a lazy commit txn when call get_rowset
// we need advance lazy commit txn here
int64_t first_txn_id = -1;
@@ -3064,13 +3214,15 @@ void MetaServiceImpl::get_rowset(::google::protobuf::RpcController* controller,
std::shared_ptr<TxnLazyCommitTask> task =
txn_lazy_committer_->submit(instance_id, first_txn_id);
- std::tie(code, msg) = task->wait();
- if (code != MetaServiceCode::OK) {
- LOG(WARNING) << "advance_last_txn failed last_txn=" << first_txn_id
- << " code=" << code << " msg=" << msg;
- return;
+ if (config::wait_txn_lazy_commit_during_reads) {
+ std::tie(code, msg) = task->wait();
+ if (code != MetaServiceCode::OK) {
+ LOG(WARNING) << "advance_last_txn failed last_txn=" << first_txn_id
+ << " code=" << code << " msg=" << msg;
+ return;
+ }
+ continue;
}
- continue;
}
}
@@ -3183,7 +3335,7 @@ void MetaServiceImpl::get_rowset(::google::protobuf::RpcController* controller,
if (!try_fetch_and_parse_schema(txn.get(), rowset_meta.mutable_tablet_schema(),
instance_id, idx.index_id(),
rowset_meta.schema_version(), code, msg,
- is_versioned_read)) {
+ is_versioned_read, resource_mgr_.get())) {
return;
}
version_to_schema.emplace(rowset_meta.schema_version(),
@@ -3217,7 +3369,7 @@ void MetaServiceImpl::get_tablet_stats(::google::protobuf::RpcController* contro
RPC_RATE_LIMIT(get_tablet_stats)
bool is_versioned_read = is_version_read_enabled(instance_id);
- MetaReader reader(instance_id, txn_kv_.get());
+ CloneChainReader reader(instance_id, txn_kv_.get(), resource_mgr_.get());
for (auto& i : request->tablet_idx()) {
TabletIndexPB idx(i);
// FIXME(plat1ko): Get all tablet stats in one txn
@@ -3393,7 +3545,8 @@ static bool remove_pending_delete_bitmap(MetaServiceCode& code, std::string& msg
static bool check_partition_version_when_update_delete_bitmap(
MetaServiceCode& code, std::string& msg, std::unique_ptr<Transaction>& txn,
std::string& instance_id, int64_t table_id, int64_t partition_id, int64_t tablet_id,
- int64_t txn_id, int64_t next_visible_version, bool is_versioned_read) {
+ int64_t txn_id, int64_t next_visible_version, bool is_versioned_read,
+ ResourceManager* resource_mgr) {
if (partition_id <= 0) {
LOG(WARNING) << fmt::format(
"invalid partition_id, skip to check partition version. txn={}, "
@@ -3467,7 +3620,7 @@ static bool check_partition_version_when_update_delete_bitmap(
}
}
} else {
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr);
VersionPB version_pb;
TxnErrorCode err =
reader.get_partition_version(txn.get(), partition_id, &version_pb, nullptr);
@@ -3556,7 +3709,8 @@ void _write_delete_bitmap_kvs(MetaServiceCode& code, std::string& msg, std::stri
size_t i, std::string& log, KVStats& stats,
const UpdateDeleteBitmapRequest* request, std::string& instance_id,
std::string& key, const std::string& val,
- UpdateDeleteBitmapTxnStats& txn_stats) {
+ UpdateDeleteBitmapTxnStats& txn_stats, bool is_versioned_read,
+ ResourceManager* resource_mgr) {
auto table_id = request->table_id();
auto tablet_id = request->tablet_id();
bool without_lock = request->has_without_lock() ? request->without_lock() : false;
@@ -3631,16 +3785,41 @@ void _write_delete_bitmap_kvs(MetaServiceCode& code, std::string& msg, std::stri
<< " tablet_id=" << tablet_id << " because the rowset does not exist";
return;
}
- auto rowset_key =
- meta_rowset_key({instance_id, tablet_id, request->pre_rowset_versions(i)});
- std::string rowset_val;
- TxnErrorCode err = txn->get(rowset_key, &rowset_val);
- if (err != TxnErrorCode::TXN_OK && TxnErrorCode::TXN_KEY_NOT_FOUND != err) {
- ss << "failed to get rowset, instance_id=" << instance_id << " tablet_id=" << tablet_id
- << " version=" << request->pre_rowset_versions(i) << " err=" << err;
- msg = ss.str();
- code = cast_as<ErrCategory::READ>(err);
- return;
+
+ TxnErrorCode err = TxnErrorCode::TXN_OK;
+ doris::RowsetMetaCloudPB rs;
+ if (!is_versioned_read) {
+ auto rowset_key =
+ meta_rowset_key({instance_id, tablet_id, request->pre_rowset_versions(i)});
+ std::string rowset_val;
+ err = txn->get(rowset_key, &rowset_val);
+ if (err != TxnErrorCode::TXN_OK && TxnErrorCode::TXN_KEY_NOT_FOUND != err) {
+ ss << "failed to get rowset, instance_id=" << instance_id
+ << " tablet_id=" << tablet_id << " version=" << request->pre_rowset_versions(i)
+ << " err=" << err;
+ msg = ss.str();
+ code = cast_as<ErrCategory::READ>(err);
+ return;
+ }
+ if (err == TxnErrorCode::TXN_OK &&
+ !rs.ParseFromArray(rowset_val.data(), rowset_val.size())) {
+ code = MetaServiceCode::PROTOBUF_PARSE_ERR;
+ ss << "malformed rowset meta, unable to deserialize, tablet_id=" << tablet_id
+ << " key=" << hex(rowset_key);
+ msg = ss.str();
+ return;
+ }
+ } else {
+ CloneChainReader reader(instance_id, resource_mgr);
+ err = reader.get_rowset_meta(txn.get(), tablet_id, request->pre_rowset_versions(i),
+ &rs);
+ if (err != TxnErrorCode::TXN_OK && TxnErrorCode::TXN_KEY_NOT_FOUND != err) {
+ ss << "failed to get versioned rowset, err=" << err << " tablet_id=" << tablet_id
+ << " version=" << request->pre_rowset_versions(i);
+ msg = ss.str();
+ code = cast_as<ErrCategory::READ>(err);
+ return;
+ }
}
if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
non_exist_rowset_ids.emplace(request->rowset_ids(i));
@@ -3649,14 +3828,6 @@ void _write_delete_bitmap_kvs(MetaServiceCode& code, std::string& msg, std::stri
<< " tablet_id=" << tablet_id << " because the rowset is not exist";
return;
}
- doris::RowsetMetaCloudPB rs;
- if (!rs.ParseFromArray(rowset_val.data(), rowset_val.size())) {
- code = MetaServiceCode::PROTOBUF_PARSE_ERR;
- ss << "malformed rowset meta, unable to deserialize, tablet_id=" << tablet_id
- << " key=" << hex(rowset_key);
- msg = ss.str();
- return;
- }
if (rs.rowset_id_v2() != request->rowset_ids(i)) {
LOG(INFO) << "skip update delete bitmap, rowset_id=" << request->rowset_ids(i)
<< " version=" << request->pre_rowset_versions(i)
@@ -3704,7 +3875,8 @@ void MetaServiceImpl::update_delete_bitmap(google::protobuf::RpcController* cont
LOG(WARNING) << msg << ", cloud_unique_id=" << request->cloud_unique_id();
return;
}
- if (request->without_lock() && request->has_pre_rowset_agg_end_version() &&
+ bool without_lock = request->has_without_lock() ? request->without_lock() : false;
+ if (without_lock && request->has_pre_rowset_agg_end_version() &&
request->pre_rowset_agg_end_version() > 0) {
if (request->rowset_ids_size() != request->pre_rowset_versions_size()) {
code = MetaServiceCode::INVALID_ARGUMENT;
@@ -3724,6 +3896,21 @@ void MetaServiceImpl::update_delete_bitmap(google::protobuf::RpcController* cont
return;
}
+ auto store_version = request->has_store_version() ? request->store_version() : 1;
+ if (store_version != 1 && store_version != 2 && store_version != 3) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "delete bitmap store version must be 1, 2, 3";
+ return;
+ }
+
+ bool is_versioned_write = is_version_write_enabled(instance_id);
+ if (!without_lock && is_versioned_write && store_version == 1) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "instance enabled versioned write, please set delete_bitmap_store_write_version to 2 "
+ "or 3 in be.conf";
+ return;
+ }
+
std::string use_version =
delete_bitmap_lock_white_list_->get_delete_bitmap_lock_version(instance_id);
RPC_RATE_LIMIT(update_delete_bitmap)
@@ -3741,7 +3928,6 @@ void MetaServiceImpl::update_delete_bitmap(google::protobuf::RpcController* cont
bool is_explicit_txn = (request->has_is_explicit_txn() && request->is_explicit_txn());
bool is_first_sub_txn = (is_explicit_txn && request->txn_id() == request->lock_id());
- bool without_lock = request->has_without_lock() ? request->without_lock() : false;
std::string log = ", update delete bitmap for tablet " + std::to_string(tablet_id);
if (!without_lock) {
// 1. Check whether the lock expires
@@ -3772,7 +3958,8 @@ void MetaServiceImpl::update_delete_bitmap(google::protobuf::RpcController* cont
bool is_versioned_read = is_version_read_enabled(instance_id);
if (!check_partition_version_when_update_delete_bitmap(
code, msg, txn, instance_id, table_id, request->partition_id(), tablet_id,
- request->txn_id(), request->next_visible_version(), is_versioned_read)) {
+ request->txn_id(), request->next_visible_version(), is_versioned_read,
+ resource_mgr_.get())) {
return;
}
}
@@ -3864,8 +4051,10 @@ void MetaServiceImpl::update_delete_bitmap(google::protobuf::RpcController* cont
for (size_t i = 0; i < delete_bitmap_keys_v1.size(); ++i) {
auto& key = delete_bitmap_keys_v1[i];
auto& val = request->segment_delete_bitmaps(i);
+ bool is_versioned_read = is_version_read_enabled(instance_id);
_write_delete_bitmap_kvs(code, msg, ss, txn_kv_, txn, use_version, non_exist_rowset_ids, i,
- log, stats, request, instance_id, key, val, txn_stats);
+ log, stats, request, instance_id, key, val, txn_stats,
+ is_versioned_read, resource_mgr_.get());
if (code != MetaServiceCode::OK) return;
}
// write v2 kvs
@@ -3881,8 +4070,10 @@ void MetaServiceImpl::update_delete_bitmap(google::protobuf::RpcController* cont
<< " rowset_id=" << request->delta_rowset_ids(i) << ", delete bitmap num="
<< request->delete_bitmap_storages(i).delete_bitmap().rowset_ids_size()
<< ". key=" << hex(key) << ", value_size=" << val.size();
+ bool is_versioned_read = is_version_read_enabled(instance_id);
_write_delete_bitmap_kvs(code, msg, ss, txn_kv_, txn, use_version, non_exist_rowset_ids, i,
- log, stats, request, instance_id, key, val, txn_stats);
+ log, stats, request, instance_id, key, val, txn_stats,
+ is_versioned_read, resource_mgr_.get());
if (code != MetaServiceCode::OK) return;
}
@@ -3996,6 +4187,14 @@ void MetaServiceImpl::get_delete_bitmap(google::protobuf::RpcController* control
return;
}
+ bool is_versioned_read = is_version_read_enabled(instance_id);
+ if (is_versioned_read && store_version == 1) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "instance enabled versioned read, please set delete_bitmap_store_read_version to 2 "
+ "or 3 in be.conf";
+ return;
+ }
+
response->set_tablet_id(tablet_id);
int64_t delete_bitmap_num = 0;
int64_t delete_bitmap_byte = 0;
@@ -4133,11 +4332,10 @@ void MetaServiceImpl::get_delete_bitmap(google::protobuf::RpcController* control
check_delete_bitmap_bytes_exceed_limit();
if (code != MetaServiceCode::OK) return;
- std::string key;
- versioned::MetaDeleteBitmapInfo key_info {instance_id, tablet_id, rowset_ids[i]};
- versioned::meta_delete_bitmap_key(key_info, &key);
- ValueBuf val_buf;
- err = cloud::blob_get(txn.get(), key, &val_buf);
+ DeleteBitmapStoragePB delete_bitmap_storage;
+ CloneChainReader reader(instance_id, resource_mgr_.get());
+ err = reader.get_delete_bitmap_v2(txn.get(), tablet_id, rowset_ids[i],
+ &delete_bitmap_storage);
int64_t retry = 0;
TEST_SYNC_POINT_CALLBACK("get_delete_bitmap_err", &retry, &err);
@@ -4152,7 +4350,8 @@ void MetaServiceImpl::get_delete_bitmap(google::protobuf::RpcController* control
msg = ss.str();
return;
}
- err = cloud::blob_get(txn.get(), key, &val_buf);
+ err = reader.get_delete_bitmap_v2(txn.get(), tablet_id, rowset_ids[i],
+ &delete_bitmap_storage);
retry++;
LOG(INFO) << "retry get delete bitmap, tablet=" << tablet_id << ", retry=" << retry
<< ", delete_bitmap_num=" << delete_bitmap_num
@@ -4164,19 +4363,15 @@ void MetaServiceImpl::get_delete_bitmap(google::protobuf::RpcController* control
LOG(INFO) << "delete bitmap not found for tablet=" << tablet_id
<< ", rowset=" << rowset_ids[i];
continue;
- }
- if (err != TxnErrorCode::TXN_OK) {
- code = cast_as<ErrCategory::READ>(err);
- ss << "failed to get delete bitmap, ret=" << err;
- msg = ss.str();
- return;
- }
- DeleteBitmapStoragePB delete_bitmap_storage;
- if (!val_buf.to_pb(&delete_bitmap_storage)) {
+ } else if (err == TxnErrorCode::TXN_INVALID_DATA) {
code = MetaServiceCode::PROTOBUF_PARSE_ERR;
ss << "failed to parse DeleteBitmapStoragePB for tablet=" << tablet_id
- << ", rowset=" << rowset_ids[i] << ", key=" << hex(key)
- << ", value_size=" << val_buf.value().size();
+ << ", rowset=" << rowset_ids[i];
+ msg = ss.str();
+ return;
+ } else if (err != TxnErrorCode::TXN_OK) {
+ code = cast_as<ErrCategory::READ>(err);
+ ss << "failed to get delete bitmap, ret=" << err;
msg = ss.str();
return;
}
@@ -4188,7 +4383,7 @@ void MetaServiceImpl::get_delete_bitmap(google::protobuf::RpcController* control
<< ", delete_bitmap_num="
<< delete_bitmap_storage.delete_bitmap().rowset_ids_size();
delete_bitmap_num += delete_bitmap_storage.delete_bitmap().rowset_ids_size();
- delete_bitmap_byte += val_buf.value().size();
+ delete_bitmap_byte += delete_bitmap_storage.ByteSizeLong();
}
response->add_returned_rowset_ids(rowset_ids[i]);
@@ -4232,7 +4427,7 @@ void MetaServiceImpl::get_delete_bitmap(google::protobuf::RpcController* control
return;
}
} else {
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr_.get());
TxnErrorCode err =
reader.get_tablet_merged_stats(txn.get(), tablet_id, &tablet_stat, nullptr);
if (err != TxnErrorCode::TXN_OK) {
@@ -4333,7 +4528,7 @@ bool MetaServiceImpl::get_mow_tablet_stats_and_meta(MetaServiceCode& code, std::
std::stringstream ss;
bool is_versioned_read = is_version_read_enabled(instance_id);
if (!config::enable_batch_get_mow_tablet_stats_and_meta) {
- MetaReader reader(instance_id, txn_kv_.get());
+ CloneChainReader reader(instance_id, txn_kv_.get(), resource_mgr_.get());
for (const auto& tablet_idx : request->tablet_indexes()) {
// 1. get compaction cnts
TabletStatsPB tablet_stat;
@@ -4521,7 +4716,7 @@ bool MetaServiceImpl::get_mow_tablet_stats_and_meta(MetaServiceCode& code, std::
}
DCHECK(request->tablet_indexes_size() == response->tablet_states_size());
} else {
- MetaReader reader(instance_id, txn_kv_.get());
+ CloneChainReader reader(instance_id, txn_kv_.get(), resource_mgr_.get());
std::vector<int64_t> tablet_ids;
tablet_ids.reserve(request->tablet_indexes_size());
for (const auto& tablet_idx : request->tablet_indexes()) {
@@ -5333,16 +5528,48 @@ std::pair<std::string, std::string> init_key_pair(std::string instance_id, int64
}
MetaServiceResponseStatus MetaServiceImpl::fix_tablet_stats(std::string cloud_unique_id_str,
- std::string table_id_str) {
+ std::string table_id_str,
+ std::string tablet_id_str) {
// parse params
int64_t table_id;
+ int64_t tablet_id = -1;
std::string instance_id;
- MetaServiceResponseStatus st = parse_fix_tablet_stats_param(
- resource_mgr_, table_id_str, cloud_unique_id_str, table_id, instance_id);
+ MetaServiceResponseStatus st =
+ parse_fix_tablet_stats_param(resource_mgr_, table_id_str, cloud_unique_id_str,
+ tablet_id_str, table_id, instance_id, tablet_id);
if (st.code() != MetaServiceCode::OK) {
return st;
}
+ bool is_versioned_read = is_version_read_enabled(instance_id);
+ bool is_versioned_write = is_version_write_enabled(instance_id);
+ if (is_versioned_write) {
+ if (tablet_id < 0) {
+ st.set_code(MetaServiceCode::INVALID_ARGUMENT);
+ st.set_msg(
+ "cannot fix tablet stats for all tablets of a table when versioned write is "
+ "enabled, consider specifying tablet_id");
+ return st;
+ }
+
+ TabletIndexPB tablet_idx;
+ CloneChainReader reader(instance_id, txn_kv_.get(), resource_mgr_.get());
+ TxnErrorCode err = reader.get_tablet_index(tablet_id, &tablet_idx);
+ if (err != TxnErrorCode::TXN_OK) {
+ st.set_code(cast_as<ErrCategory::READ>(err));
+ st.set_msg(fmt::format("failed to get tablet index for tablet_id={}, err={}", tablet_id,
+ err));
+ return st;
+ }
+
+ auto&& [code, msg] = fix_versioned_tablet_stats_internal(
+ txn_kv_.get(), instance_id, tablet_idx, is_versioned_read, is_versioned_write,
+ resource_mgr_.get());
+ st.set_code(code);
+ st.set_msg(std::move(msg));
+ return st;
+ }
+
std::pair<std::string, std::string> key_pair = init_key_pair(instance_id, table_id);
std::string old_begin_key;
while (old_begin_key < key_pair.first) {
@@ -5376,6 +5603,47 @@ MetaServiceResponseStatus MetaServiceImpl::fix_tablet_stats(std::string cloud_un
return st;
}
+std::pair<MetaServiceCode, std::string> MetaServiceImpl::fix_tablet_db_id(
+ const std::string& instance_id, int64_t tablet_id, int64_t db_id) {
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return {cast_as<ErrCategory::CREATE>(err), "failed to init txn"};
+ }
+
+ TabletIndexPB tablet_index_pb;
+ std::string key = meta_tablet_idx_key({instance_id, tablet_id});
+ std::string value;
+ err = txn->get(key, &value);
+ if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ std::string msg = fmt::format("tablet index pb not found, key={}", hex(key));
+ return {MetaServiceCode::TABLET_NOT_FOUND, msg};
+ } else if (err != TxnErrorCode::TXN_OK) {
+ std::string msg =
+ fmt::format("failed to get tablet index pb, key={}, err={}", hex(key), err);
+ return {cast_as<ErrCategory::READ>(err), msg};
+ } else if (!tablet_index_pb.ParseFromString(value)) {
+ std::string msg = fmt::format("failed to parse TabletIndexPB, key={}", hex(key));
+ return {MetaServiceCode::PROTOBUF_PARSE_ERR, msg};
+ } else if (tablet_index_pb.db_id() == db_id) {
+ LOG(INFO) << "no need to fix tablet db id, same db id, tablet_id=" << tablet_id
+ << ", db_id=" << db_id;
+ return {MetaServiceCode::OK, ""};
+ }
+
+ tablet_index_pb.set_db_id(db_id);
+ txn->put(key, tablet_index_pb.SerializeAsString());
+ err = txn->commit();
+ if (err != TxnErrorCode::TXN_OK) {
+ std::string msg = fmt::format(
+ "failed to commit txn to fix tablet db id, tablet_id={}, db_id={}, err={}",
+ tablet_id, db_id, err);
+ return {cast_as<ErrCategory::COMMIT>(err), msg};
+ }
+
+ return {MetaServiceCode::OK, ""};
+}
+
std::size_t get_segments_key_bounds_bytes(const doris::RowsetMetaCloudPB& rowset_meta) {
size_t ret {0};
for (const auto& key_bounds : rowset_meta.segments_key_bounds()) {
@@ -5462,4 +5730,42 @@ std::string hide_access_key(const std::string& ak) {
return key;
}
+std::pair<MetaServiceCode, std::string> MetaServiceImpl::wait_for_pending_txns(
+ const std::string& instance_id, std::vector<VersionPB>& versions) {
+ std::vector<std::shared_ptr<TxnLazyCommitTask>> tasks;
+ for (auto& version : versions) {
+ if (version.pending_txn_ids_size() == 0) {
+ continue;
+ }
+
+ DCHECK_EQ(version.pending_txn_ids_size(), 1)
+ << "only support one pending txn id for now, version="
+ << version.ShortDebugString();
+
+ int64_t first_txn_id = version.pending_txn_ids(0);
+ std::shared_ptr<TxnLazyCommitTask> task =
+ txn_lazy_committer_->submit(instance_id, first_txn_id);
+ tasks.push_back(task);
+ }
+
+ for (auto& task : tasks) {
+ auto&& [code, msg] = task->wait();
+ if (code != MetaServiceCode::OK) {
+ LOG(WARNING) << "wait for pending txn " << task->txn_id() << " failed, code=" << code
+ << " msg=" << msg;
+ return {code, msg};
+ }
+ }
+
+ for (auto& version : versions) {
+ if (version.pending_txn_ids_size() == 0) {
+ continue;
+ }
+ version.clear_pending_txn_ids();
+ version.set_version(version.version() + 1);
+ }
+
+ return {MetaServiceCode::OK, ""};
+}
+
} // namespace doris::cloud
diff --git a/cloud/src/meta-service/meta_service.h b/cloud/src/meta-service/meta_service.h
index 0e5ca28aee6..36e9113b77d 100644
--- a/cloud/src/meta-service/meta_service.h
+++ b/cloud/src/meta-service/meta_service.h
@@ -363,7 +363,10 @@ public:
InstanceInfoPB* instance);
MetaServiceResponseStatus fix_tablet_stats(std::string cloud_unique_id_str,
- std::string table_id_str);
+ std::string table_id_str, std::string tablet_id_str);
+
+ std::pair<MetaServiceCode, std::string> fix_tablet_db_id(const std::string& instance_id,
+ int64_t tablet_id, int64_t db_id);
void get_delete_bitmap_lock_version(std::string& use_version, std::string& instance_id);
@@ -371,6 +374,10 @@ public:
const BeginSnapshotRequest* request, BeginSnapshotResponse* response,
::google::protobuf::Closure* done) override;
+ void update_snapshot(::google::protobuf::RpcController* controller,
+ const UpdateSnapshotRequest* request, UpdateSnapshotResponse* response,
+ ::google::protobuf::Closure* done) override;
+
void commit_snapshot(::google::protobuf::RpcController* controller,
const CommitSnapshotRequest* request, CommitSnapshotResponse* response,
::google::protobuf::Closure* done) override;
@@ -394,7 +401,8 @@ public:
private:
std::pair<MetaServiceCode, std::string> alter_instance(
const AlterInstanceRequest* request,
- std::function<std::pair<MetaServiceCode, std::string>(InstanceInfoPB*)> action);
+ std::function<std::pair<MetaServiceCode, std::string>(Transaction*, InstanceInfoPB*)>
+ action);
bool get_mow_tablet_stats_and_meta(MetaServiceCode& code, std::string& msg,
const GetDeleteBitmapUpdateLockRequest* request,
@@ -470,6 +478,14 @@ private:
const GetVersionRequest* request, GetVersionResponse* response,
std::string_view instance_id, KVStats& stats);
+ void commit_partition_internal(const PartitionRequest* request, const std::string& instance_id,
+ const std::vector<int64_t>& partition_ids, MetaServiceCode& code,
+ std::string& msg, KVStats& stats);
+
+ // Wait for all pending transactions before returning, and bump up the version to the latest.
+ std::pair<MetaServiceCode, std::string> wait_for_pending_txns(const std::string& instance_id,
+ std::vector<VersionPB>& versions);
+
std::shared_ptr<TxnKv> txn_kv_;
std::shared_ptr<ResourceManager> resource_mgr_;
std::shared_ptr<RateLimiter> rate_limiter_;
@@ -492,6 +508,12 @@ public:
[[nodiscard]] const std::shared_ptr<ResourceManager>& resource_mgr() const {
return impl_->resource_mgr();
}
+ [[nodiscard]] const std::shared_ptr<TxnLazyCommitter>& txn_lazy_committer() const {
+ return impl_->txn_lazy_committer();
+ }
+ [[nodiscard]] const std::shared_ptr<SnapshotManager>& snapshot_manager() const {
+ return impl_->snapshot_manager();
+ }
void begin_txn(::google::protobuf::RpcController* controller, const BeginTxnRequest* request,
BeginTxnResponse* response, ::google::protobuf::Closure* done) override {
@@ -901,6 +923,12 @@ public:
call_impl(&cloud::MetaService::begin_snapshot, controller, request, response, done);
}
+ void update_snapshot(::google::protobuf::RpcController* controller,
+ const UpdateSnapshotRequest* request, UpdateSnapshotResponse* response,
+ ::google::protobuf::Closure* done) override {
+ call_impl(&cloud::MetaService::update_snapshot, controller, request, response, done);
+ }
+
void commit_snapshot(::google::protobuf::RpcController* controller,
const CommitSnapshotRequest* request, CommitSnapshotResponse* response,
::google::protobuf::Closure* done) override {
diff --git a/cloud/src/meta-service/meta_service_helper.h b/cloud/src/meta-service/meta_service_helper.h
index d59b4ec1829..b992f5deb72 100644
--- a/cloud/src/meta-service/meta_service_helper.h
+++ b/cloud/src/meta-service/meta_service_helper.h
@@ -217,7 +217,9 @@ void finish_rpc(std::string_view func_name, brpc::Controller* ctrl, const Reques
<< " status=" << res->status().ShortDebugString();
} else if constexpr (std::is_same_v<Response, GetObjStoreInfoResponse> ||
std::is_same_v<Response, GetStageResponse> ||
- std::is_same_v<Response, GetInstanceResponse>) {
+ std::is_same_v<Response, GetInstanceResponse> ||
+ std::is_same_v<Response, BeginSnapshotResponse> ||
+ std::is_same_v<Response, CloneInstanceResponse>) {
std::string debug_string = encryt_sk(res->DebugString());
debug_string = hide_ak(debug_string);
TEST_SYNC_POINT_CALLBACK("sk_finish_rpc", &debug_string);
@@ -358,7 +360,7 @@ int decrypt_instance_info(InstanceInfoPB& instance, const std::string& instance_
* Notifies other metaservice to refresh instance
*/
void notify_refresh_instance(std::shared_ptr<TxnKv> txn_kv, const std::string& instance_id,
- KVStats* stats);
+ KVStats* stats, bool include_self = false);
void get_tablet_idx(MetaServiceCode& code, std::string& msg, Transaction* txn,
const std::string& instance_id, int64_t tablet_id, TabletIndexPB& tablet_idx);
diff --git a/cloud/src/meta-service/meta_service_http.cpp b/cloud/src/meta-service/meta_service_http.cpp
index c6608e813a9..ff2c4ce080d 100644
--- a/cloud/src/meta-service/meta_service_http.cpp
+++ b/cloud/src/meta-service/meta_service_http.cpp
@@ -41,7 +41,6 @@
#include <string>
#include <string_view>
#include <type_traits>
-#include <variant>
#include <vector>
#include "common/config.h"
@@ -49,7 +48,6 @@
#include "common/logging.h"
#include "common/string_util.h"
#include "meta-service/meta_service_helper.h"
-#include "meta-store/keys.h"
#include "meta-store/txn_kv.h"
#include "meta-store/txn_kv_error.h"
#include "meta_service.h"
@@ -105,6 +103,7 @@ std::tuple<int, std::string_view> convert_ms_code_to_http_code(MetaServiceCode r
case PROTOBUF_PARSE_ERR:
return {400, "INVALID_ARGUMENT"};
case CLUSTER_NOT_FOUND:
+ case TABLET_NOT_FOUND:
return {404, "NOT_FOUND"};
case ALREADY_EXISTED:
return {409, "ALREADY_EXISTED"};
@@ -610,12 +609,41 @@ static HttpResponse process_fix_tablet_stats(MetaServiceImpl* service, brpc::Con
auto& uri = ctrl->http_request().uri();
std::string_view cloud_unique_id = http_query(uri, "cloud_unique_id");
std::string_view table_id = http_query(uri, "table_id");
+ std::string_view tablet_id = http_query(uri, "tablet_id");
- MetaServiceResponseStatus st =
- service->fix_tablet_stats(std::string(cloud_unique_id), std::string(table_id));
+ MetaServiceResponseStatus st = service->fix_tablet_stats(
+ std::string(cloud_unique_id), std::string(table_id), std::string(tablet_id));
return http_text_reply(st, st.DebugString());
}
+static HttpResponse process_fix_tablet_db_id(MetaServiceImpl* service, brpc::Controller* ctrl) {
+ auto& uri = ctrl->http_request().uri();
+ std::string instance_id(http_query(uri, "instance_id"));
+ std::string tablet_id_str(http_query(uri, "tablet_id"));
+ std::string db_id_str(http_query(uri, "db_id"));
+
+ int64_t tablet_id = 0, db_id = 0;
+ try {
+ db_id = std::stol(db_id_str);
+ } catch (const std::exception& e) {
+ auto msg = fmt::format("db_id {} must be a number, meet error={}", db_id_str, e.what());
+ LOG(WARNING) << msg;
+ return http_json_reply(MetaServiceCode::INVALID_ARGUMENT, msg);
+ }
+
+ try {
+ tablet_id = std::stol(tablet_id_str);
+ } catch (const std::exception& e) {
+ auto msg = fmt::format("tablet_id {} must be a number, meet error={}", tablet_id_str,
+ e.what());
+ LOG(WARNING) << msg;
+ return http_json_reply(MetaServiceCode::INVALID_ARGUMENT, msg);
+ }
+
+ auto [code, msg] = service->fix_tablet_db_id(instance_id, tablet_id, db_id);
+ return http_text_reply(code, msg, "");
+}
+
static HttpResponse process_get_stage(MetaServiceImpl* service, brpc::Controller* ctrl) {
GetStageRequest req;
PARSE_MESSAGE_OR_RETURN(ctrl, req);
@@ -678,6 +706,32 @@ static HttpResponse process_set_snapshot_property(MetaServiceImpl* service,
brpc::Controller* ctrl) {
AlterInstanceRequest req;
PARSE_MESSAGE_OR_RETURN(ctrl, req);
+ auto* properties = req.mutable_properties();
+ if (properties->contains("status")) {
+ std::string status = properties->at("status");
+ if (status != "ENABLED" && status != "DISABLED") {
+ return http_json_reply(MetaServiceCode::INVALID_ARGUMENT,
+ "Invalid value for status property: " + status +
+ ", expected 'ENABLED' or 'DISABLED' (case insensitive)");
+ }
+ std::string_view is_enable = (status == "ENABLED") ? "true" : "false";
+ const std::string& property_name =
+ AlterInstanceRequest::SnapshotProperty_Name(AlterInstanceRequest::ENABLE_SNAPSHOT);
+ (*properties)[property_name] = is_enable;
+ properties->erase("status");
+ }
+ if (properties->contains("max_reserved_snapshots")) {
+ const std::string& property_name = AlterInstanceRequest::SnapshotProperty_Name(
+ AlterInstanceRequest::MAX_RESERVED_SNAPSHOTS);
+ (*properties)[property_name] = properties->at("max_reserved_snapshots");
+ properties->erase("max_reserved_snapshots");
+ }
+ if (properties->contains("snapshot_interval_seconds")) {
+ const std::string& property_name = AlterInstanceRequest::SnapshotProperty_Name(
+ AlterInstanceRequest::SNAPSHOT_INTERVAL_SECONDS);
+ (*properties)[property_name] = properties->at("snapshot_interval_seconds");
+ properties->erase("snapshot_interval_seconds");
+ }
req.set_op(AlterInstanceRequest::SET_SNAPSHOT_PROPERTY);
AlterInstanceResponse resp;
service->alter_instance(ctrl, &req, &resp, nullptr);
@@ -687,12 +741,18 @@ static HttpResponse process_set_snapshot_property(MetaServiceImpl* service,
static HttpResponse process_set_multi_version_status(MetaServiceImpl* service,
brpc::Controller* ctrl) {
auto& uri = ctrl->http_request().uri();
- std::string cloud_unique_id(http_query(uri, "cloud_unique_id"));
std::string instance_id(http_query(uri, "instance_id"));
+ std::string cloud_unique_id(http_query(uri, "cloud_unique_id"));
std::string multi_version_status_str(http_query(uri, "multi_version_status"));
- if (cloud_unique_id.empty() || instance_id.empty() || multi_version_status_str.empty()) {
- return http_json_reply(MetaServiceCode::INVALID_ARGUMENT, "missing required arguments");
+ // Prefer instance_id if provided, fallback to cloud_unique_id
+ if (instance_id.empty()) {
+ return http_json_reply(MetaServiceCode::INVALID_ARGUMENT, "empty instance id");
+ }
+
+ if (multi_version_status_str.empty()) {
+ return http_json_reply(MetaServiceCode::INVALID_ARGUMENT,
+ "multi_version_status is required");
}
// Parse multi_version_status from string to enum
@@ -716,8 +776,9 @@ static HttpResponse process_set_multi_version_status(MetaServiceImpl* service,
"MULTI_VERSION_WRITE_ONLY, MULTI_VERSION_READ_WRITE, MULTI_VERSION_ENABLED");
}
// Call snapshot manager directly
- auto [code, msg] = service->snapshot_manager()->set_multi_version_status(
- instance_id, cloud_unique_id, multi_version_status);
+ auto [code, msg] = service->snapshot_manager()->set_multi_version_status(instance_id,
+ multi_version_status);
+
return http_json_reply(code, msg);
}
@@ -742,44 +803,38 @@ static HttpResponse process_get_snapshot_property(MetaServiceImpl* service,
// Build snapshot properties response
rapidjson::Document doc;
doc.SetObject();
- auto& allocator = doc.GetAllocator();
-
- // Add snapshot properties
- rapidjson::Value properties(rapidjson::kObjectType);
// Snapshot switch status
- std::string switch_status;
+ std::string_view switch_status;
switch (instance.snapshot_switch_status()) {
case SNAPSHOT_SWITCH_DISABLED:
- switch_status = "disabled";
+ switch_status = "UNSUPPORTED";
break;
case SNAPSHOT_SWITCH_OFF:
- switch_status = "false";
+ switch_status = "DISABLED";
break;
case SNAPSHOT_SWITCH_ON:
- switch_status = "true";
+ switch_status = "ENABLED";
break;
default:
- switch_status = "unknown";
+ switch_status = "UNKNOWN";
break;
}
- properties.AddMember("enabled", rapidjson::Value(switch_status.c_str(), allocator), allocator);
+ doc.AddMember("status", rapidjson::StringRef(switch_status.data(), switch_status.size()),
+ doc.GetAllocator());
// Max reserved snapshots
if (instance.has_max_reserved_snapshot()) {
- properties.AddMember("max_reserved_snapshots", instance.max_reserved_snapshot(), allocator);
+ doc.AddMember("max_reserved_snapshots", instance.max_reserved_snapshot(),
+ doc.GetAllocator());
}
// Snapshot interval seconds
if (instance.has_snapshot_interval_seconds()) {
- properties.AddMember("snapshot_interval_seconds", instance.snapshot_interval_seconds(),
- allocator);
+ doc.AddMember("snapshot_interval_seconds", instance.snapshot_interval_seconds(),
+ doc.GetAllocator());
}
- doc.AddMember("code", "OK", allocator);
- doc.AddMember("msg", "", allocator);
- doc.AddMember("result", properties, allocator);
-
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
@@ -853,6 +908,7 @@ void MetaServiceImpl::http(::google::protobuf::RpcController* controller,
{"txn_lazy_commit", process_txn_lazy_commit},
{"injection_point", process_injection_point},
{"fix_tablet_stats", process_fix_tablet_stats},
+ {"fix_tablet_db_id", process_fix_tablet_db_id},
{"v1/decode_key", process_decode_key},
{"v1/encode_key", process_encode_key},
{"v1/get_value", process_get_value},
@@ -861,6 +917,7 @@ void MetaServiceImpl::http(::google::protobuf::RpcController* controller,
{"v1/txn_lazy_commit", process_txn_lazy_commit},
{"v1/injection_point", process_injection_point},
{"v1/fix_tablet_stats", process_fix_tablet_stats},
+ {"v1/fix_tablet_db_id", process_fix_tablet_db_id},
// for get
{"get_instance", process_get_instance_info},
{"get_obj_store_info", process_get_obj_store_info},
diff --git a/cloud/src/meta-service/meta_service_job.cpp b/cloud/src/meta-service/meta_service_job.cpp
index 0ea6f2d9483..6ffe6f1e506 100644
--- a/cloud/src/meta-service/meta_service_job.cpp
+++ b/cloud/src/meta-service/meta_service_job.cpp
@@ -37,6 +37,8 @@
#include "meta-service/meta_service.h"
#include "meta-service/meta_service_helper.h"
#include "meta-service/meta_service_tablet_stats.h"
+#include "meta-store/blob_message.h"
+#include "meta-store/clone_chain_reader.h"
#include "meta-store/document_message.h"
#include "meta-store/keys.h"
#include "meta-store/meta_reader.h"
@@ -44,6 +46,7 @@
#include "meta-store/txn_kv_error.h"
#include "meta-store/versioned_value.h"
#include "meta_service.h"
+#include "resource-manager/resource_manager.h"
// Empty string not is not processed
template <typename T, size_t S>
@@ -97,7 +100,8 @@ bool check_compaction_input_verions(const TabletCompactionJobPB& compaction,
void start_compaction_job(MetaServiceCode& code, std::string& msg, std::stringstream& ss,
std::unique_ptr<Transaction>& txn, const StartTabletJobRequest* request,
StartTabletJobResponse* response, std::string& instance_id,
- bool& need_commit, bool is_versioned_read) {
+ bool& need_commit, bool is_versioned_read,
+ ResourceManager* resource_mgr) {
auto& compaction = request->job().compaction(0);
if (!compaction.has_id() || compaction.id().empty()) {
code = MetaServiceCode::INVALID_ARGUMENT;
@@ -147,7 +151,7 @@ void start_compaction_job(MetaServiceCode& code, std::string& msg, std::stringst
}
CHECK(stats.ParseFromString(stats_val));
} else {
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr);
TxnErrorCode err = reader.get_tablet_compact_stats(txn.get(), tablet_id, &stats, nullptr);
if (err != TxnErrorCode::TXN_OK) {
code = err == TxnErrorCode::TXN_KEY_NOT_FOUND ? MetaServiceCode::TABLET_NOT_FOUND
@@ -301,7 +305,8 @@ void start_compaction_job(MetaServiceCode& code, std::string& msg, std::stringst
void start_schema_change_job(MetaServiceCode& code, std::string& msg, std::stringstream& ss,
std::unique_ptr<Transaction>& txn,
const StartTabletJobRequest* request, StartTabletJobResponse* response,
- std::string& instance_id, bool& need_commit, bool is_versioned_read) {
+ std::string& instance_id, bool& need_commit, bool is_versioned_read,
+ ResourceManager* resource_mgr) {
auto& schema_change = request->job().schema_change();
if (!schema_change.has_id() || schema_change.id().empty()) {
code = MetaServiceCode::INVALID_ARGUMENT;
@@ -331,7 +336,7 @@ void start_schema_change_job(MetaServiceCode& code, std::string& msg, std::strin
return;
}
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr);
auto& new_tablet_idx = const_cast<TabletIndexPB&>(schema_change.new_tablet_idx());
if (!new_tablet_idx.has_table_id() || !new_tablet_idx.has_index_id() ||
!new_tablet_idx.has_partition_id()) {
@@ -492,7 +497,7 @@ void MetaServiceImpl::start_tablet_job(::google::protobuf::RpcController* contro
get_tablet_idx(code, msg, txn.get(), instance_id, tablet_id, tablet_idx);
if (code != MetaServiceCode::OK) return;
} else {
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr_.get());
err = reader.get_tablet_index(txn.get(), tablet_id, &tablet_idx);
if (err != TxnErrorCode::TXN_OK) {
code = err == TxnErrorCode::TXN_KEY_NOT_FOUND ? MetaServiceCode::TABLET_NOT_FOUND
@@ -526,13 +531,13 @@ void MetaServiceImpl::start_tablet_job(::google::protobuf::RpcController* contro
if (!request->job().compaction().empty()) {
start_compaction_job(code, msg, ss, txn, request, response, instance_id, need_commit,
- is_versioned_read);
+ is_versioned_read, resource_mgr_.get());
return;
}
if (request->job().has_schema_change()) {
start_schema_change_job(code, msg, ss, txn, request, response, instance_id, need_commit,
- is_versioned_read);
+ is_versioned_read, resource_mgr_.get());
return;
}
}
@@ -832,7 +837,7 @@ void process_compaction_job(MetaServiceCode& code, std::string& msg, std::string
FinishTabletJobResponse* response, TabletJobInfoPB& recorded_job,
std::string& instance_id, std::string& job_key, bool& need_commit,
std::string& use_version, bool is_versioned_read,
- bool is_versioned_write, TxnKv* txn_kv) {
+ bool is_versioned_write, TxnKv* txn_kv, ResourceManager* resource_mgr) {
//==========================================================================
// check
//==========================================================================
@@ -949,17 +954,30 @@ void process_compaction_job(MetaServiceCode& code, std::string& msg, std::string
//==========================================================================
auto stats = response->mutable_stats();
- MetaReader meta_reader(instance_id);
+ CloneChainReader meta_reader(instance_id, resource_mgr);
TabletStats detached_stats;
if (is_versioned_read) {
- TxnErrorCode err =
- meta_reader.get_tablet_compact_stats(txn.get(), tablet_id, stats, nullptr, true);
+ // The compact stats = tablet stats, the load stats = detached stats
+ TxnErrorCode err = meta_reader.get_tablet_compact_stats(
+ txn.get(), tablet_id, stats, nullptr, config::snapshot_get_tablet_stats);
+ if (err != TxnErrorCode::TXN_OK) {
+ code = cast_as<ErrCategory::READ>(err);
+ msg = fmt::format("failed to get tablet compact stats, tablet_id={}, err={}", tablet_id,
+ err);
+ LOG(WARNING) << msg;
+ return;
+ }
+ TabletStatsPB load_stats;
+ err = meta_reader.get_tablet_load_stats(txn.get(), tablet_id, &load_stats, nullptr,
+ config::snapshot_get_tablet_stats);
if (err != TxnErrorCode::TXN_OK) {
code = cast_as<ErrCategory::READ>(err);
- msg = fmt::format("failed to get tablet stats, tablet_id={}, err={}", tablet_id, err);
+ msg = fmt::format("failed to get tablet load stats, tablet_id={}, err={}", tablet_id,
+ err);
LOG(WARNING) << msg;
return;
}
+ detach_tablet_stats(load_stats, detached_stats);
} else {
// ATTN: The condition that snapshot read can be used to get tablet stats is: all other transactions that put tablet stats
// can make read write conflicts with this transaction on other keys. Currently, if all meta-service nodes are running
@@ -976,68 +994,10 @@ void process_compaction_job(MetaServiceCode& code, std::string& msg, std::string
}
}
- if (is_versioned_write) {
- // read old TabletCompactStatsKey -> TabletStatsPB
- TabletStatsPB tablet_compact_stats;
- TxnErrorCode err = TxnErrorCode::TXN_OK;
- if (is_versioned_read) {
- // Reuse the above txn::get result.
- tablet_compact_stats.CopyFrom(*stats);
- } else {
- err = meta_reader.get_tablet_compact_stats(txn.get(), tablet_id, &tablet_compact_stats,
- nullptr, false);
- }
- if (err == TxnErrorCode::TXN_OK) {
- // tablet_compact_stats exists, update TabletStatsPB
- if (compaction_update_tablet_stats(compaction, &tablet_compact_stats, code, msg, now) ==
- -1) {
- LOG_WARNING("compaction_update_tablet_stats failed.")
- .tag("instance_id", instance_id)
- .tag("tablet_id", tablet_id)
- .tag("compact_stats", tablet_compact_stats.ShortDebugString());
- return;
- }
- } else if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
- // First time switching from single write to double write mode
- // Step 1: Copy from single version stats as baseline
- tablet_compact_stats.CopyFrom(*stats);
- // Step 2: Reset size fields to zero because compact_stats + load_stats = single_stats
- // Since data_size/index_size are inherited by load_stats, compact_stats must start from 0
- tablet_compact_stats.set_num_rows(0);
- tablet_compact_stats.set_data_size(0);
- tablet_compact_stats.set_num_rowsets(0);
- tablet_compact_stats.set_num_segments(0);
- tablet_compact_stats.set_index_size(0);
- tablet_compact_stats.set_segment_size(0);
- // Step 3: Apply compaction updates
- if (compaction_update_tablet_stats(compaction, &tablet_compact_stats, code, msg, now) ==
- -1) {
- LOG_WARNING("first set compaction_update_tablet_stats failed.")
- .tag("tablet_id", tablet_id)
- .tag("compact_stats", tablet_compact_stats.ShortDebugString());
- return;
- }
- } else if (err != TxnErrorCode::TXN_OK) {
- code = cast_as<ErrCategory::READ>(err);
- msg = fmt::format("failed to get tablet compact stats, tablet_id={}, err={}", tablet_id,
- err);
- return;
- }
- // Write new TabletCompactStatsKey -> TabletStatsPB for versioned storage
- auto tablet_compact_stats_val = tablet_compact_stats.SerializeAsString();
- std::string tablet_compact_stats_version_key =
- versioned::tablet_compact_stats_key({instance_id, tablet_id});
- LOG_INFO("put versioned tablet compact stats key")
- .tag("compact_stats_key", hex(tablet_compact_stats_version_key))
- .tag("tablet_id", tablet_id)
- .tag("value_size", tablet_compact_stats_val.size())
- .tag("instance_id", instance_id);
- versioned_put(txn.get(), tablet_compact_stats_version_key, tablet_compact_stats_val);
- }
-
if (compaction_update_tablet_stats(compaction, stats, code, msg, now) == -1) {
return;
}
+
auto stats_key = stats_tablet_key({instance_id, table_id, index_id, partition_id, tablet_id});
auto stats_val = stats->SerializeAsString();
@@ -1056,8 +1016,20 @@ void process_compaction_job(MetaServiceCode& code, std::string& msg, std::string
<< " compaction.size_output_rowsets=" << compaction.size_output_rowsets()
<< " compaction.size_input_rowsets=" << compaction.size_input_rowsets();
txn->put(stats_key, stats_val);
+
+ if (is_versioned_write) {
+ std::string compact_stats_key =
+ versioned::tablet_compact_stats_key({instance_id, tablet_id});
+ LOG_INFO("put versioned tablet compact stats key")
+ .tag("compact_stats_key", hex(compact_stats_key))
+ .tag("tablet_id", tablet_id)
+ .tag("value_size", stats_val.size())
+ .tag("instance_id", instance_id);
+ versioned_put(txn.get(), compact_stats_key, stats_val);
+ }
+
merge_tablet_stats(*stats, detached_stats); // this is to check
- if (!is_versioned_read && (stats->data_size() < 0 || stats->num_rowsets() < 1)) [[unlikely]] {
+ if (stats->data_size() < 0 || stats->num_rowsets() < 1) [[unlikely]] {
INSTANCE_LOG(ERROR) << "buggy data size, tablet_id=" << tablet_id
<< " stats.num_rows=" << stats->num_rows()
<< " stats.data_size=" << stats->data_size()
@@ -1137,6 +1109,11 @@ void process_compaction_job(MetaServiceCode& code, std::string& msg, std::string
RecycleRowsetPB recycle_rowset;
recycle_rowset.set_creation_time(now);
recycle_rowset.mutable_rowset_meta()->CopyFrom(rs);
+ if (config::enable_recycle_rowset_strip_key_bounds) {
+ // Strip key bounds to shrink operation log for ts compaction recycle entries
+ recycle_rowset.mutable_rowset_meta()->clear_segments_key_bounds();
+ recycle_rowset.mutable_rowset_meta()->clear_segments_key_bounds_truncated();
+ }
recycle_rowset.set_type(RecycleRowsetPB::COMPACT);
if (is_versioned_write) {
@@ -1144,10 +1121,9 @@ void process_compaction_job(MetaServiceCode& code, std::string& msg, std::string
} else {
auto recycle_val = recycle_rowset.SerializeAsString();
txn->put(recycle_key, recycle_val);
+ INSTANCE_LOG(INFO) << "put recycle rowset, tablet_id=" << tablet_id
+ << " key=" << hex(recycle_key);
}
-
- INSTANCE_LOG(INFO) << "put recycle rowset, tablet_id=" << tablet_id
- << " key=" << hex(recycle_key);
};
if (!is_versioned_read) {
std::tie(code, msg) =
@@ -1301,29 +1277,19 @@ void process_compaction_job(MetaServiceCode& code, std::string& msg, std::string
need_commit = true;
if (!compaction_log.recycle_rowsets().empty() && is_versioned_write) {
+ size_t num_recycled_rowsets = compaction_log.recycle_rowsets().size();
std::string operation_log_key = versioned::log_key({instance_id});
- std::string operation_log_value;
OperationLogPB operation_log;
if (is_versioned_read) {
operation_log.set_min_timestamp(meta_reader.min_read_version());
}
operation_log.mutable_compaction()->Swap(&compaction_log);
- if (!operation_log.SerializeToString(&operation_log_value)) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- msg = fmt::format("failed to serialize OperationLogPB: {}", hex(operation_log_key));
- LOG_WARNING(msg)
- .tag("instance_id", instance_id)
- .tag("table_id", request->job().idx().table_id());
- return;
- }
- // Put versioned operation log for compaction to track recycling
- LOG_INFO("put versioned operation log key")
+ versioned::blob_put(txn.get(), operation_log_key, operation_log);
+ LOG_INFO("put compaction operation log key")
.tag("instance_id", instance_id)
.tag("operation_log_key", hex(operation_log_key))
.tag("tablet_id", tablet_id)
- .tag("value_size", operation_log_value.size())
- .tag("recycle_rowsets_count", compaction_log.recycle_rowsets().size());
- versioned_put(txn.get(), operation_log_key, operation_log_value);
+ .tag("recycle_rowsets_count", num_recycled_rowsets);
}
}
@@ -1353,29 +1319,6 @@ void schema_change_update_tablet_stats(const TabletSchemaChangeJobPB& schema_cha
segment_size_remove_rowsets));
}
-std::pair<TabletStatsPB, TabletStatsPB> split_tablet_stats_into_load_and_compact_parts(
- const TabletStatsPB& stats) {
- TabletStatsPB load_stats, compact_stats;
- compact_stats.set_base_compaction_cnt(stats.base_compaction_cnt());
- compact_stats.set_cumulative_compaction_cnt(stats.cumulative_compaction_cnt());
- compact_stats.set_cumulative_point(stats.cumulative_point());
- compact_stats.set_last_base_compaction_time_ms(stats.last_base_compaction_time_ms());
- compact_stats.set_last_cumu_compaction_time_ms(stats.last_cumu_compaction_time_ms());
- compact_stats.set_full_compaction_cnt(stats.full_compaction_cnt());
- compact_stats.set_last_full_compaction_time_ms(stats.last_full_compaction_time_ms());
- compact_stats.mutable_idx()->CopyFrom(stats.idx());
-
- load_stats.set_num_rows(stats.num_rows());
- load_stats.set_num_rowsets(stats.num_rowsets());
- load_stats.set_num_segments(stats.num_segments());
- load_stats.set_data_size(stats.data_size());
- load_stats.set_index_size(stats.index_size());
- load_stats.set_segment_size(stats.segment_size());
- load_stats.mutable_idx()->CopyFrom(stats.idx());
-
- return {load_stats, compact_stats};
-}
-
std::pair<MetaServiceCode, std::string> scan_schema_change_input_rowsets(
Transaction* txn, std::string_view instance_id, int64_t new_tablet_id,
std::string& rs_start, std::string& rs_end, auto&& callback) {
@@ -1417,7 +1360,8 @@ void process_schema_change_job(MetaServiceCode& code, std::string& msg, std::str
FinishTabletJobResponse* response, TabletJobInfoPB& recorded_job,
std::string& instance_id, std::string& job_key, bool& need_commit,
std::string& use_version, bool is_versioned_read,
- bool is_versioned_write, TxnKv* txn_kv) {
+ bool is_versioned_write, TxnKv* txn_kv,
+ ResourceManager* resource_mgr) {
//==========================================================================
// check
//==========================================================================
@@ -1439,7 +1383,7 @@ void process_schema_change_job(MetaServiceCode& code, std::string& msg, std::str
msg = "not allow new_tablet_id same with base_tablet_id";
return;
}
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr);
auto& new_tablet_idx = const_cast<TabletIndexPB&>(schema_change.new_tablet_idx());
if (!new_tablet_idx.has_table_id() || !new_tablet_idx.has_index_id() ||
!new_tablet_idx.has_partition_id()) {
@@ -1637,13 +1581,7 @@ void process_schema_change_job(MetaServiceCode& code, std::string& msg, std::str
if (is_versioned_write) {
std::string versioned_new_tablet_key =
versioned::meta_tablet_key({instance_id, new_tablet_id});
- if (!versioned::document_put(txn.get(), versioned_new_tablet_key,
- std::move(new_tablet_meta))) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- msg = fmt::format("failed to serialize versioned tablet meta, key={}",
- hex(versioned_new_tablet_key));
- return;
- }
+ versioned_put(txn.get(), versioned_new_tablet_key, new_tablet_val);
LOG(INFO) << "put versioned new tablet meta, new_tablet_id=" << new_tablet_id
<< " key=" << hex(versioned_new_tablet_key);
}
@@ -1723,6 +1661,11 @@ void process_schema_change_job(MetaServiceCode& code, std::string& msg, std::str
RecycleRowsetPB recycle_rowset;
recycle_rowset.set_creation_time(now);
recycle_rowset.mutable_rowset_meta()->CopyFrom(rs);
+ if (config::enable_recycle_rowset_strip_key_bounds) {
+ // Strip key bounds to shrink schema change recycle operation log entries
+ recycle_rowset.mutable_rowset_meta()->clear_segments_key_bounds();
+ recycle_rowset.mutable_rowset_meta()->clear_segments_key_bounds_truncated();
+ }
recycle_rowset.set_type(RecycleRowsetPB::DROP);
if (is_versioned_write) {
schema_change_log.add_recycle_rowsets()->Swap(&recycle_rowset);
@@ -1767,15 +1710,27 @@ void process_schema_change_job(MetaServiceCode& code, std::string& msg, std::str
auto stats = response->mutable_stats();
TabletStats detached_stats;
if (is_versioned_read) {
- TxnErrorCode err =
- reader.get_tablet_merged_stats(txn.get(), new_tablet_id, stats, nullptr, true);
+ TxnErrorCode err = reader.get_tablet_compact_stats(txn.get(), new_tablet_id, stats, nullptr,
+ config::snapshot_get_tablet_stats);
if (err != TxnErrorCode::TXN_OK) {
code = cast_as<ErrCategory::READ>(err);
- msg = fmt::format("failed to get tablet stats, tablet_id={}, err={}", new_tablet_id,
- err);
+ msg = fmt::format("failed to get tablet compact stats, tablet_id={}, err={}",
+ new_tablet_id, err);
+ LOG(WARNING) << msg;
+ return;
+ }
+
+ TabletStatsPB load_stats;
+ err = reader.get_tablet_load_stats(txn.get(), new_tablet_id, &load_stats, nullptr,
+ config::snapshot_get_tablet_stats);
+ if (err != TxnErrorCode::TXN_OK) {
+ code = cast_as<ErrCategory::READ>(err);
+ msg = fmt::format("failed to get tablet load stats, tablet_id={}, err={}",
+ new_tablet_id, err);
LOG(WARNING) << msg;
return;
}
+ detach_tablet_stats(load_stats, detached_stats);
} else {
// ATTN: The condition that snapshot read can be used to get tablet stats is: all other transactions that put tablet stats
// can make read write conflicts with this transaction on other keys. Currently, if all meta-service nodes are running
@@ -1791,66 +1746,27 @@ void process_schema_change_job(MetaServiceCode& code, std::string& msg, std::str
return;
}
}
- if (is_versioned_write) {
- // read new TabletLoadStatsKey -> TabletStatsPB
- TabletStatsPB new_tablet_stats;
- MetaReader meta_reader(instance_id, txn_kv);
- Versionstamp* versionstamp = nullptr;
- TxnErrorCode err = TxnErrorCode::TXN_OK;
- if (is_versioned_read) {
- new_tablet_stats.CopyFrom(*stats);
- } else {
- err = meta_reader.get_tablet_merged_stats(txn.get(), new_tablet_id, &new_tablet_stats,
- versionstamp, false);
- }
- if (err == TxnErrorCode::TXN_OK) {
- // new_tablet_load_stats exists, update TabletStatsPB
- schema_change_update_tablet_stats(schema_change, &new_tablet_stats, num_remove_rows,
- size_remove_rowsets, num_remove_rowsets,
- num_remove_segments, index_size_remove_rowsets,
- segment_size_remove_rowsets);
- } else if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
- // First time switching from single write to double write mode
- // Step 1: Copy from single version stats as baseline
- new_tablet_stats.CopyFrom(*stats);
- // Step 2: Apply schema change updates
- schema_change_update_tablet_stats(schema_change, &new_tablet_stats, num_remove_rows,
- size_remove_rowsets, num_remove_rowsets,
- num_remove_segments, index_size_remove_rowsets,
- segment_size_remove_rowsets);
- } else if (err != TxnErrorCode::TXN_OK) {
- code = cast_as<ErrCategory::READ>(err);
- msg = fmt::format("failed to get tablet compact stats, tablet_id={}, err={}", tablet_id,
- err);
- return;
- }
+ schema_change_update_tablet_stats(schema_change, stats, num_remove_rows, size_remove_rowsets,
+ num_remove_rowsets, num_remove_segments,
+ index_size_remove_rowsets, segment_size_remove_rowsets);
+ auto stats_key = stats_tablet_key(
+ {instance_id, new_table_id, new_index_id, new_partition_id, new_tablet_id});
+ auto stats_val = stats->SerializeAsString();
+ txn->put(stats_key, stats_val);
- auto [load_stats, compact_stats] =
- split_tablet_stats_into_load_and_compact_parts(new_tablet_stats);
- std::string load_value = load_stats.SerializeAsString();
- std::string compact_value = compact_stats.SerializeAsString();
- std::string load_stats_key = versioned::tablet_load_stats_key({instance_id, new_tablet_id});
+ if (is_versioned_write) {
std::string compact_stats_key =
versioned::tablet_compact_stats_key({instance_id, new_tablet_id});
+ versioned_put(txn.get(), compact_stats_key, stats_val);
- LOG_INFO("put versioned tablet load/compact stats key")
+ LOG_INFO("put versioned tablet compact stats key")
.tag("tablet_id", tablet_id)
.tag("new_tablet_id", new_tablet_id)
- .tag("load_value_size", load_value.size())
- .tag("compact_value_size", compact_value.size())
- .tag("load_stats_key", hex(load_stats_key))
+ .tag("compact_value_size", stats_val.size())
.tag("compact_stats_key", hex(compact_stats_key))
.tag("instance_id", instance_id);
- versioned_put(txn.get(), load_stats_key, load_value);
- versioned_put(txn.get(), compact_stats_key, compact_value);
}
- schema_change_update_tablet_stats(schema_change, stats, num_remove_rows, size_remove_rowsets,
- num_remove_rowsets, num_remove_segments,
- index_size_remove_rowsets, segment_size_remove_rowsets);
- auto stats_key = stats_tablet_key(
- {instance_id, new_table_id, new_index_id, new_partition_id, new_tablet_id});
- auto stats_val = stats->SerializeAsString();
- txn->put(stats_key, stats_val);
+
merge_tablet_stats(*stats, detached_stats);
VLOG_DEBUG << "update tablet stats tablet_id=" << tablet_id << " key=" << hex(stats_key)
<< " stats=" << proto_to_json(*stats);
@@ -1906,8 +1822,7 @@ void process_schema_change_job(MetaServiceCode& code, std::string& msg, std::str
txn->put(rowset_key, rowset_val);
txn->remove(tmp_rowset_key);
if (is_versioned_write) {
- doris::RowsetMetaCloudPB rs_meta;
- rs_meta.ParseFromString(tmp_rowset_val);
+ doris::RowsetMetaCloudPB rs_meta(tmp_rowset_meta);
std::string meta_rowset_compact_key = versioned::meta_rowset_compact_key(
{instance_id, new_tablet_id, rs_meta.end_version()});
// Put versioned rowset compact metadata for new tablet's rowsets
@@ -1966,29 +1881,18 @@ void process_schema_change_job(MetaServiceCode& code, std::string& msg, std::str
if (is_versioned_write) {
std::string operation_log_key = versioned::log_key({instance_id});
- std::string operation_log_value;
OperationLogPB operation_log;
if (is_versioned_read) {
operation_log.set_min_timestamp(reader.min_read_version());
}
operation_log.mutable_schema_change()->Swap(&schema_change_log);
- if (!operation_log.SerializeToString(&operation_log_value)) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- msg = fmt::format("failed to serialize OperationLogPB: {}", hex(operation_log_key));
- LOG_WARNING(msg)
- .tag("instance_id", instance_id)
- .tag("table_id", request->job().idx().table_id());
- return;
- }
- // Put versioned operation log for compaction to track recycling
- LOG_INFO("put versioned operation log key")
+ versioned::blob_put(txn.get(), operation_log_key, operation_log);
+ LOG_INFO("put schema change operation log key")
.tag("instance_id", instance_id)
.tag("operation_log_key", hex(operation_log_key))
.tag("tablet_id", tablet_id)
.tag("new_tablet_id", new_tablet_id)
- .tag("value_size", operation_log_value.size())
.tag("recycle_rowsets_count", schema_change_log.recycle_rowsets().size());
- versioned_put(txn.get(), operation_log_key, operation_log_value);
}
}
@@ -2039,7 +1943,7 @@ void MetaServiceImpl::finish_tablet_job(::google::protobuf::RpcController* contr
get_tablet_idx(code, msg, txn.get(), instance_id, tablet_id, tablet_idx);
if (code != MetaServiceCode::OK) return;
} else {
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr_.get());
err = reader.get_tablet_index(txn.get(), tablet_id, &tablet_idx);
if (err != TxnErrorCode::TXN_OK) {
code = err == TxnErrorCode::TXN_KEY_NOT_FOUND
@@ -2090,12 +1994,13 @@ void MetaServiceImpl::finish_tablet_job(::google::protobuf::RpcController* contr
// Process compaction commit
process_compaction_job(code, msg, ss, txn, request, response, recorded_job, instance_id,
job_key, need_commit, use_version, is_versioned_read,
- is_versioned_write, txn_kv_.get());
+ is_versioned_write, txn_kv_.get(), resource_mgr_.get());
} else if (request->job().has_schema_change()) {
// Process schema change commit
process_schema_change_job(code, msg, ss, txn, request, response, recorded_job,
instance_id, job_key, need_commit, use_version,
- is_versioned_read, is_versioned_write, txn_kv_.get());
+ is_versioned_read, is_versioned_write, txn_kv_.get(),
+ resource_mgr_.get());
}
if (!need_commit) return;
diff --git a/cloud/src/meta-service/meta_service_partition.cpp b/cloud/src/meta-service/meta_service_partition.cpp
index c8a642add92..811fc219b99 100644
--- a/cloud/src/meta-service/meta_service_partition.cpp
+++ b/cloud/src/meta-service/meta_service_partition.cpp
@@ -21,9 +21,12 @@
#include <chrono>
#include <memory>
+#include "common/defer.h"
#include "common/logging.h"
#include "common/stats.h"
#include "meta-service/meta_service_helper.h"
+#include "meta-store/blob_message.h"
+#include "meta-store/clone_chain_reader.h"
#include "meta-store/keys.h"
#include "meta-store/meta_reader.h"
#include "meta-store/txn_kv_error.h"
@@ -107,7 +110,7 @@ void MetaServiceImpl::prepare_index(::google::protobuf::RpcController* controlle
return;
}
bool is_versioned_read = is_version_read_enabled(instance_id);
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr_.get());
if (!is_versioned_read) {
err = index_exists(txn.get(), instance_id, request);
} else {
@@ -202,7 +205,14 @@ void MetaServiceImpl::commit_index(::google::protobuf::RpcController* controller
commit_index_log.set_table_id(request->table_id());
bool is_versioned_read = is_version_read_enabled(instance_id);
- MetaReader reader(instance_id);
+ bool is_versioned_write = is_version_write_enabled(instance_id);
+ if (!request->has_db_id()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "db_id is required for versioned write, please upgrade your FE version";
+ return;
+ }
+
+ CloneChainReader reader(instance_id, resource_mgr_.get());
for (auto index_id : request->index_ids()) {
auto key = recycle_index_key({instance_id, index_id});
std::string val;
@@ -250,7 +260,7 @@ void MetaServiceImpl::commit_index(::google::protobuf::RpcController* controller
txn->remove(key);
// Save the index meta/index keys
- if (request->has_db_id() && is_version_write_enabled(instance_id)) {
+ if (is_versioned_write) {
int64_t db_id = request->db_id();
int64_t table_id = request->table_id();
std::string index_meta_key = versioned::meta_index_key({instance_id, index_id});
@@ -276,7 +286,38 @@ void MetaServiceImpl::commit_index(::google::protobuf::RpcController* controller
}
}
- if (request->has_db_id() && request->has_is_new_table() && request->is_new_table()) {
+ // Save the partition meta keys
+ if (is_versioned_write) {
+ for (auto partition_id : request->partition_ids()) {
+ int64_t db_id = request->db_id();
+ int64_t table_id = request->table_id();
+ std::string part_meta_key = versioned::meta_partition_key({instance_id, partition_id});
+ std::string part_index_key =
+ versioned::partition_index_key({instance_id, partition_id});
+ std::string part_inverted_index_key = versioned::partition_inverted_index_key(
+ {instance_id, db_id, table_id, partition_id});
+ PartitionIndexPB part_index_pb;
+ part_index_pb.set_db_id(db_id);
+ part_index_pb.set_table_id(table_id);
+ std::string part_index_value;
+ if (!part_index_pb.SerializeToString(&part_index_value)) {
+ code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
+ msg = fmt::format("failed to serialize PartitionIndexPB");
+ LOG_WARNING(msg).tag("part_id", partition_id);
+ return;
+ }
+ versioned_put(txn.get(), part_meta_key, "");
+ txn->put(part_inverted_index_key, "");
+ txn->put(part_index_key, part_index_value);
+
+ LOG(INFO) << "xxx put versioned partition index key=" << hex(part_index_key)
+ << " partition_id=" << partition_id;
+
+ commit_index_log.add_partition_ids(partition_id);
+ }
+ }
+
+ if (request->has_is_new_table() && request->is_new_table()) {
if (is_versioned_read) {
// Read the table version, to build the operation log visible version range.
Versionstamp table_version;
@@ -294,19 +335,16 @@ void MetaServiceImpl::commit_index(::google::protobuf::RpcController* controller
if (commit_index_log.index_ids_size() > 0 && is_version_write_enabled(instance_id)) {
std::string operation_log_key = versioned::log_key({instance_id});
- std::string operation_log_value;
OperationLogPB operation_log;
if (is_versioned_read) {
operation_log.set_min_timestamp(reader.min_read_version());
}
operation_log.mutable_commit_index()->Swap(&commit_index_log);
- if (!operation_log.SerializeToString(&operation_log_value)) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- msg = fmt::format("failed to serialize OperationLogPB: {}", hex(operation_log_key));
- LOG_WARNING(msg).tag("instance_id", instance_id).tag("table_id", request->table_id());
- return;
- }
- versioned_put(txn.get(), operation_log_key, operation_log_value);
+ versioned::blob_put(txn.get(), operation_log_key, operation_log);
+ LOG_INFO("put commit index operation log key")
+ .tag("instance_id", instance_id)
+ .tag("table_id", request->table_id())
+ .tag("operation_log_key", hex(operation_log_key));
}
err = txn->commit();
@@ -355,12 +393,19 @@ void MetaServiceImpl::drop_index(::google::protobuf::RpcController* controller,
bool need_commit = false;
bool is_versioned_write = is_version_write_enabled(instance_id);
bool is_versioned_read = is_version_read_enabled(instance_id);
+
+ if (is_versioned_write && !request->has_db_id()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "missing db_id for versioned write, please upgrade your FE version";
+ return;
+ }
+
DropIndexLogPB drop_index_log;
drop_index_log.set_db_id(request->db_id());
drop_index_log.set_table_id(request->table_id());
drop_index_log.set_expiration(request->expiration());
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr_.get());
for (auto index_id : request->index_ids()) {
auto key = recycle_index_key({instance_id, index_id});
std::string val;
@@ -418,23 +463,15 @@ void MetaServiceImpl::drop_index(::google::protobuf::RpcController* controller,
if (drop_index_log.index_ids_size() > 0 && is_versioned_write) {
std::string operation_log_key = versioned::log_key({instance_id});
- std::string operation_log_value;
OperationLogPB operation_log;
if (is_versioned_read) {
operation_log.set_min_timestamp(reader.min_read_version());
}
operation_log.mutable_drop_index()->Swap(&drop_index_log);
- if (!operation_log.SerializeToString(&operation_log_value)) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- msg = fmt::format("failed to serialize OperationLogPB: {}", hex(operation_log_key));
- LOG_WARNING(msg).tag("instance_id", instance_id).tag("table_id", request->table_id());
- return;
- }
- versioned_put(txn.get(), operation_log_key, operation_log_value);
+ versioned::blob_put(txn.get(), operation_log_key, operation_log);
LOG(INFO) << "put drop index operation log"
<< " instance_id=" << instance_id << " table_id=" << request->table_id()
- << " index_ids=" << drop_index_log.index_ids_size()
- << " log_size=" << operation_log_value.size();
+ << " index_ids=" << drop_index_log.index_ids_size();
}
err = txn->commit();
@@ -503,7 +540,7 @@ void MetaServiceImpl::prepare_partition(::google::protobuf::RpcController* contr
if (!is_versioned_read) {
err = partition_exists(txn.get(), instance_id, request);
} else {
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr_.get());
err = reader.is_partition_exists(txn.get(), request->partition_ids(0));
}
// If index has existed, this might be a stale request
@@ -611,6 +648,26 @@ void MetaServiceImpl::commit_partition(::google::protobuf::RpcController* contro
return;
}
+ constexpr size_t BATCH_COMMIT_SIZE = 1000;
+ for (size_t i = 0; i < request->partition_ids_size(); i += BATCH_COMMIT_SIZE) {
+ std::vector<int64_t> partition_ids;
+ size_t end = std::min(i + BATCH_COMMIT_SIZE, (size_t)request->partition_ids_size());
+ for (size_t j = i; j < end; j++) {
+ partition_ids.push_back(request->partition_ids(j));
+ }
+ commit_partition_internal(request, instance_id, partition_ids, code, msg, stats);
+ if (code != MetaServiceCode::OK) {
+ return;
+ }
+ }
+}
+
+void MetaServiceImpl::commit_partition_internal(const PartitionRequest* request,
+ const std::string& instance_id,
+ const std::vector<int64_t>& partition_ids,
+ MetaServiceCode& code, std::string& msg,
+ KVStats& stats) {
+ std::unique_ptr<Transaction> txn;
TxnErrorCode err = txn_kv_->create_txn(&txn);
if (err != TxnErrorCode::TXN_OK) {
code = cast_as<ErrCategory::CREATE>(err);
@@ -618,14 +675,33 @@ void MetaServiceImpl::commit_partition(::google::protobuf::RpcController* contro
return;
}
+ DORIS_CLOUD_DEFER {
+ if (txn) {
+ stats.get_bytes += txn->get_bytes();
+ stats.put_bytes += txn->put_bytes();
+ stats.del_bytes += txn->delete_bytes();
+ stats.get_counter += txn->num_get_keys();
+ stats.put_counter += txn->num_put_keys();
+ stats.del_counter += txn->num_del_keys();
+ }
+ };
+
CommitPartitionLogPB commit_partition_log;
commit_partition_log.set_db_id(request->db_id());
commit_partition_log.set_table_id(request->table_id());
commit_partition_log.mutable_index_ids()->CopyFrom(request->index_ids());
bool is_versioned_read = is_version_read_enabled(instance_id);
- MetaReader reader(instance_id);
- for (auto part_id : request->partition_ids()) {
+ bool is_versioned_write = is_version_write_enabled(instance_id);
+ if (is_versioned_write && !request->has_db_id()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "missing db_id for versioned write, please upgrade your FE version";
+ return;
+ }
+
+ CloneChainReader reader(instance_id, resource_mgr_.get());
+ size_t num_commit = 0;
+ for (auto part_id : partition_ids) {
auto key = recycle_partition_key({instance_id, part_id});
std::string val;
err = txn->get(key, &val);
@@ -639,7 +715,8 @@ void MetaServiceImpl::commit_partition(::google::protobuf::RpcController* contro
}
// If partition has existed, this might be a duplicate request
if (err == TxnErrorCode::TXN_OK) {
- return; // Partition committed, OK
+ // Partition committed, OK
+ continue;
}
if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
code = cast_as<ErrCategory::READ>(err);
@@ -673,9 +750,10 @@ void MetaServiceImpl::commit_partition(::google::protobuf::RpcController* contro
}
LOG_INFO("remove recycle partition").tag("key", hex(key));
txn->remove(key);
+ num_commit += 1;
// Save the partition meta/index keys
- if (request->has_db_id() && is_version_write_enabled(instance_id)) {
+ if (is_versioned_write) {
int64_t db_id = request->db_id();
int64_t table_id = request->table_id();
std::string part_meta_key = versioned::meta_partition_key({instance_id, part_id});
@@ -701,36 +779,37 @@ void MetaServiceImpl::commit_partition(::google::protobuf::RpcController* contro
}
}
+ if (num_commit == 0) {
+ // All partitions have been committed, OK
+ return;
+ }
+
// update table versions
- if (request->has_db_id()) {
- if (is_versioned_read) {
- // Read the table version, to build the operation log visible version range.
- Versionstamp table_version;
- err = reader.get_table_version(txn.get(), request->table_id(), &table_version, true);
- if (err != TxnErrorCode::TXN_OK && err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
- code = cast_as<ErrCategory::READ>(err);
- msg = fmt::format("failed to get table version, err={}", err);
- return;
- }
+ if (is_versioned_read) {
+ // Read the table version, to build the operation log visible version range.
+ Versionstamp table_version;
+ err = reader.get_table_version(txn.get(), request->table_id(), &table_version, true);
+ if (err != TxnErrorCode::TXN_OK && err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ code = cast_as<ErrCategory::READ>(err);
+ msg = fmt::format("failed to get table version, err={}", err);
+ return;
}
- update_table_version(txn.get(), instance_id, request->db_id(), request->table_id());
}
+ update_table_version(txn.get(), instance_id, request->db_id(), request->table_id());
if (commit_partition_log.partition_ids_size() > 0 && is_version_write_enabled(instance_id)) {
std::string operation_log_key = versioned::log_key({instance_id});
- std::string operation_log_value;
OperationLogPB operation_log;
if (is_versioned_read) {
operation_log.set_min_timestamp(reader.min_read_version());
}
operation_log.mutable_commit_partition()->Swap(&commit_partition_log);
- if (!operation_log.SerializeToString(&operation_log_value)) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- msg = fmt::format("failed to serialize OperationLogPB: {}", hex(operation_log_key));
- LOG_WARNING(msg).tag("instance_id", instance_id).tag("table_id", request->table_id());
- return;
- }
- versioned_put(txn.get(), operation_log_key, operation_log_value);
+ versioned::blob_put(txn.get(), operation_log_key, operation_log);
+ LOG_INFO("put commit partition operation log key")
+ .tag("instance_id", instance_id)
+ .tag("table_id", request->table_id())
+ .tag("num_partitions", operation_log.commit_partition().partition_ids_size())
+ .tag("operation_log_key", hex(operation_log_key));
}
err = txn->commit();
@@ -760,6 +839,12 @@ void MetaServiceImpl::drop_partition(::google::protobuf::RpcController* controll
return;
}
+ if (!request->has_db_id()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "missing db_id for drop_partition";
+ return;
+ }
+
TxnErrorCode err = txn_kv_->create_txn(&txn);
if (err != TxnErrorCode::TXN_OK) {
code = cast_as<ErrCategory::READ>(err);
@@ -786,7 +871,7 @@ void MetaServiceImpl::drop_partition(::google::protobuf::RpcController* controll
drop_partition_log.mutable_index_ids()->CopyFrom(request->index_ids());
drop_partition_log.set_expired_at_s(request->expiration());
- MetaReader reader(instance_id);
+ CloneChainReader reader(instance_id, resource_mgr_.get());
for (auto part_id : request->partition_ids()) {
auto key = recycle_partition_key({instance_id, part_id});
std::string val;
@@ -843,8 +928,7 @@ void MetaServiceImpl::drop_partition(::google::protobuf::RpcController* controll
if (!need_commit) return;
// Update table version only when deleting non-empty partitions
- if (request->has_db_id() && request->has_need_update_table_version() &&
- request->need_update_table_version()) {
+ if (request->has_need_update_table_version() && request->need_update_table_version()) {
if (is_versioned_read) {
// Read the table version, to build the operation log visible version range.
Versionstamp table_version;
@@ -863,23 +947,15 @@ void MetaServiceImpl::drop_partition(::google::protobuf::RpcController* controll
drop_partition_log.partition_ids_size() > 0) &&
is_versioned_write) {
std::string operation_log_key = versioned::log_key({instance_id});
- std::string operation_log_value;
OperationLogPB operation_log;
if (is_versioned_read) {
operation_log.set_min_timestamp(reader.min_read_version());
}
operation_log.mutable_drop_partition()->Swap(&drop_partition_log);
- if (!operation_log.SerializeToString(&operation_log_value)) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- msg = fmt::format("failed to serialize OperationLogPB: {}", hex(operation_log_key));
- LOG_WARNING(msg).tag("instance_id", instance_id).tag("table_id", request->table_id());
- return;
- }
- versioned_put(txn.get(), operation_log_key, operation_log_value);
+ versioned::blob_put(txn.get(), operation_log_key, operation_log);
LOG(INFO) << "put drop partition operation log"
<< " instance_id=" << instance_id << " table_id=" << request->table_id()
- << " partition_ids=" << drop_partition_log.partition_ids_size()
- << " log_size=" << operation_log_value.size();
+ << " partition_ids=" << drop_partition_log.partition_ids_size();
}
err = txn->commit();
diff --git a/cloud/src/meta-service/meta_service_resource.cpp b/cloud/src/meta-service/meta_service_resource.cpp
index 0c016cbbecf..7df96f3e727 100644
--- a/cloud/src/meta-service/meta_service_resource.cpp
+++ b/cloud/src/meta-service/meta_service_resource.cpp
@@ -21,12 +21,15 @@
#include <gen_cpp/cloud.pb.h>
#include <algorithm>
+#include <cctype>
#include <charconv>
#include <chrono>
#include <numeric>
+#include <queue>
#include <regex>
#include <string>
#include <tuple>
+#include <unordered_set>
#include "common/bvars.h"
#include "common/config.h"
@@ -39,6 +42,7 @@
#include "meta-service/meta_service.h"
#include "meta-service/meta_service_helper.h"
#include "meta-store/keys.h"
+#include "meta-store/meta_reader.h"
#include "meta-store/txn_kv.h"
#include "meta-store/txn_kv_error.h"
@@ -47,10 +51,6 @@ using namespace std::chrono;
namespace {
constexpr char pattern_str[] = "^[a-zA-Z][0-9a-zA-Z_]*$";
-constexpr char SNAPSHOT_ENABLED_KEY[] = "enabled";
-constexpr char SNAPSHOT_MAX_RESERVED_KEY[] = "max_reserved_snapshots";
-constexpr char SNAPSHOT_INTERVAL_SECONDS_KEY[] = "snapshot_interval_seconds";
-
bool is_valid_storage_vault_name(const std::string& str) {
const std::regex pattern(pattern_str);
return std::regex_match(str, pattern);
@@ -201,16 +201,16 @@ static int decrypt_and_update_ak_sk(ObjectStoreInfoPB& obj_info, MetaServiceCode
// Asynchronously notify refresh instance in background thread
static void async_notify_refresh_instance(
- std::shared_ptr<TxnKv> txn_kv, const std::string& instance_id,
+ std::shared_ptr<TxnKv> txn_kv, const std::string& instance_id, bool include_self,
std::function<void(const KVStats&)> stats_handler = nullptr) {
- auto f = new std::function<void()>(
- [instance_id, txn_kv = std::move(txn_kv), stats_handler = std::move(stats_handler)] {
- KVStats stats;
- notify_refresh_instance(txn_kv, instance_id, &stats);
- if (stats_handler) {
- stats_handler(stats);
- }
- });
+ auto f = new std::function<void()>([instance_id, include_self, txn_kv = std::move(txn_kv),
+ stats_handler = std::move(stats_handler)] {
+ KVStats stats;
+ notify_refresh_instance(txn_kv, instance_id, &stats, include_self);
+ if (stats_handler) {
+ stats_handler(stats);
+ }
+ });
bthread_t bid;
if (bthread_start_background(&bid, nullptr, run_bthread_work, f) != 0) {
LOG(WARNING) << "notify refresh instance inplace, instance_id=" << instance_id;
@@ -218,6 +218,233 @@ static void async_notify_refresh_instance(
}
}
+// Find all instances that need cascade update using BFS traversal
+// Returns 0 on success, -1 on error
+// Uses separate read-only transactions to avoid read conflicts with the main write transaction
+static int collect_direct_derived_instances(TxnKv* txn_kv, const std::string& source_instance_id,
+ std::vector<std::string>* derived_ids) {
+ if (!derived_ids) {
+ return -1;
+ }
+ derived_ids->clear();
+
+ if (source_instance_id.empty()) {
+ return 0;
+ }
+
+ constexpr Versionstamp kMinVersionstamp = Versionstamp::min();
+
+ std::string key_start =
+ versioned::snapshot_reference_key_prefix(source_instance_id, kMinVersionstamp);
+ std::string key_end =
+ versioned::snapshot_reference_key_prefix(source_instance_id + '\x00', kMinVersionstamp);
+ std::string current_start = key_start;
+
+ std::unique_ptr<RangeGetIterator> it;
+ while (true) {
+ std::unique_ptr<Transaction> read_txn;
+ TxnErrorCode err = txn_kv->create_txn(&read_txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to create read transaction for snapshot reference scan, err="
+ << err << " source_instance_id=" << source_instance_id;
+ return -1;
+ }
+
+ err = read_txn->get(current_start, key_end, &it);
+ if (err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to scan snapshot reference keys, err=" << err
+ << " source_instance_id=" << source_instance_id;
+ return -1;
+ }
+
+ while (it->has_next()) {
+ auto [key, value] = it->next();
+ std::string derived_id;
+ std::string_view key_view = key;
+ if (versioned::decode_snapshot_ref_key(&key_view, nullptr, nullptr, &derived_id) &&
+ !derived_id.empty()) {
+ derived_ids->push_back(std::move(derived_id));
+ } else {
+ LOG(WARNING) << "failed to decode snapshot reference key for source_instance_id="
+ << source_instance_id << " key=" << hex(key);
+ }
+ }
+
+ if (!it->more()) {
+ break;
+ }
+
+ current_start = it->next_begin_key();
+ if (current_start.empty() || current_start >= key_end) {
+ break;
+ }
+ }
+
+ return 0;
+}
+
+static int find_cascade_instances(TxnKv* txn_kv, const std::string& root_instance_id,
+ std::vector<std::string>* out) {
+ std::queue<std::string> to_visit;
+ std::unordered_set<std::string> visited;
+ std::vector<std::string> direct_children;
+
+ to_visit.push(root_instance_id);
+ visited.insert(root_instance_id);
+
+ while (!to_visit.empty()) {
+ std::string current_instance_id = to_visit.front();
+ to_visit.pop();
+
+ if (collect_direct_derived_instances(txn_kv, current_instance_id, &direct_children) != 0) {
+ LOG(WARNING) << "failed to collect derived instances for source_instance_id="
+ << current_instance_id;
+ return -1;
+ }
+
+ for (auto& derived_id : direct_children) {
+ if (derived_id.empty() || visited.contains(derived_id)) {
+ continue;
+ }
+
+ out->push_back(derived_id);
+ to_visit.push(derived_id);
+ visited.insert(derived_id);
+ LOG(INFO) << "found derived instance: " << derived_id
+ << " from source: " << current_instance_id;
+ }
+ }
+
+ LOG(INFO) << "find_cascade_instances completed, found " << out->size()
+ << " instances to cascade from root: " << root_instance_id;
+ return 0;
+}
+
+// Helper function to update AK/SK for a single instance
+// Returns 0 on success, -1 on error
+static int update_instance_ak_sk(InstanceInfoPB& instance, const UpdateAkSkRequest* request,
+ uint64_t time, MetaServiceCode& code, std::string& msg,
+ std::stringstream& update_record) {
+ // Update ram_user if has ram_user
+ if (request->has_ram_user()) {
+ if (request->ram_user().user_id().empty() || request->ram_user().ak().empty() ||
+ request->ram_user().sk().empty()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "ram user info err " + proto_to_json(*request);
+ return -1;
+ }
+ if (!instance.has_ram_user()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "instance doesn't have ram user info";
+ return -1;
+ }
+ auto& ram_user = request->ram_user();
+ EncryptionInfoPB encryption_info;
+ AkSkPair cipher_ak_sk_pair;
+ if (encrypt_ak_sk_helper(ram_user.ak(), ram_user.sk(), &encryption_info, &cipher_ak_sk_pair,
+ code, msg) != 0) {
+ return -1;
+ }
+ const auto& [ak, sk] = cipher_ak_sk_pair;
+ auto& instance_ram_user = *instance.mutable_ram_user();
+ if (ram_user.user_id() != instance_ram_user.user_id()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "ram user_id err";
+ return -1;
+ }
+ std::string old_ak = instance_ram_user.ak();
+ std::string old_sk = instance_ram_user.sk();
+ if (old_ak == ak && old_sk == sk) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "ak sk eq original, please check it";
+ return -1;
+ }
+ instance_ram_user.set_ak(std::move(cipher_ak_sk_pair.first));
+ instance_ram_user.set_sk(std::move(cipher_ak_sk_pair.second));
+ instance_ram_user.mutable_encryption_info()->CopyFrom(encryption_info);
+ update_record << "update ram_user's ak sk, instance_id: " << instance.instance_id()
+ << " user_id: " << ram_user.user_id() << " old: cipher ak: " << old_ak
+ << " cipher sk: " << old_sk << " new: cipher ak: " << ak
+ << " cipher sk: " << sk << "; ";
+ }
+
+ // Update internal_bucket_user
+ bool has_found_alter_obj_info = false;
+ for (auto& alter_bucket_user : request->internal_bucket_user()) {
+ if (!alter_bucket_user.has_ak() || !alter_bucket_user.has_sk() ||
+ !alter_bucket_user.has_user_id()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "s3 bucket info err " + proto_to_json(*request);
+ return -1;
+ }
+ std::string user_id = alter_bucket_user.user_id();
+ EncryptionInfoPB encryption_info;
+ AkSkPair cipher_ak_sk_pair;
+ if (encrypt_ak_sk_helper(alter_bucket_user.ak(), alter_bucket_user.sk(), &encryption_info,
+ &cipher_ak_sk_pair, code, msg) != 0) {
+ return -1;
+ }
+ const auto& [ak, sk] = cipher_ak_sk_pair;
+ auto& obj_info =
+ const_cast<std::decay_t<decltype(instance.obj_info())>&>(instance.obj_info());
+ for (auto& it : obj_info) {
+ std::string old_ak = it.ak();
+ std::string old_sk = it.sk();
+ if (!it.has_user_id()) {
+ has_found_alter_obj_info = true;
+ // For compatibility, obj_info without a user_id only allow
+ // single internal_bucket_user to modify it.
+ if (request->internal_bucket_user_size() != 1) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "fail to update old instance's obj_info, s3 obj info err " +
+ proto_to_json(*request);
+ return -1;
+ }
+ if (it.ak() == ak && it.sk() == sk) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "ak sk eq original, please check it";
+ return -1;
+ }
+ it.set_mtime(time);
+ it.set_user_id(user_id);
+ it.set_ak(ak);
+ it.set_sk(sk);
+ it.mutable_encryption_info()->CopyFrom(encryption_info);
+ update_record << "update obj_info's ak sk without user_id, instance_id: "
+ << instance.instance_id() << " obj_info_id: " << it.id()
+ << " new user_id: " << user_id << " old: cipher ak: " << old_ak
+ << " cipher sk: " << old_sk << " new: cipher ak: " << ak
+ << " cipher sk: " << sk << "; ";
+ continue;
+ }
+ if (it.user_id() == user_id) {
+ has_found_alter_obj_info = true;
+ if (it.ak() == ak && it.sk() == sk) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "ak sk eq original, please check it";
+ return -1;
+ }
+ it.set_mtime(time);
+ it.set_ak(ak);
+ it.set_sk(sk);
+ it.mutable_encryption_info()->CopyFrom(encryption_info);
+ update_record << "update obj_info's ak sk, instance_id: " << instance.instance_id()
+ << " obj_info_id: " << it.id() << " user_id: " << user_id
+ << " old: cipher ak: " << old_ak << " cipher sk: " << old_sk
+ << " new: cipher ak: " << ak << " cipher sk: " << sk << "; ";
+ }
+ }
+ }
+
+ if (!request->internal_bucket_user().empty() && !has_found_alter_obj_info) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "fail to find the alter obj info";
+ return -1;
+ }
+
+ return 0;
+}
+
void MetaServiceImpl::get_obj_store_info(google::protobuf::RpcController* controller,
const GetObjStoreInfoRequest* request,
GetObjStoreInfoResponse* response,
@@ -1256,6 +1483,7 @@ void MetaServiceImpl::alter_storage_vault(google::protobuf::RpcController* contr
return;
}
+ txn->atomic_add(system_meta_service_instance_update_key(), 1);
txn->put(key, val);
LOG(INFO) << "put instance_id=" << instance_id << " instance_key=" << hex(key);
err = txn->commit();
@@ -1487,6 +1715,7 @@ void MetaServiceImpl::alter_obj_store_info(google::protobuf::RpcController* cont
return;
}
+ txn->atomic_add(system_meta_service_instance_update_key(), 1);
txn->put(key, val);
LOG(INFO) << "put instance_id=" << instance_id << " instance_key=" << hex(key);
err = txn->commit();
@@ -1555,119 +1784,8 @@ void MetaServiceImpl::update_ak_sk(google::protobuf::RpcController* controller,
std::stringstream update_record;
- // if has ram_user, encrypt and save it
- if (request->has_ram_user()) {
- if (request->ram_user().user_id().empty() || request->ram_user().ak().empty() ||
- request->ram_user().sk().empty()) {
- code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "ram user info err " + proto_to_json(*request);
- return;
- }
- if (!instance.has_ram_user()) {
- code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "instance doesn't have ram user info";
- return;
- }
- auto& ram_user = request->ram_user();
- EncryptionInfoPB encryption_info;
- AkSkPair cipher_ak_sk_pair;
- if (encrypt_ak_sk_helper(ram_user.ak(), ram_user.sk(), &encryption_info, &cipher_ak_sk_pair,
- code, msg) != 0) {
- return;
- }
- const auto& [ak, sk] = cipher_ak_sk_pair;
- auto& instance_ram_user = *instance.mutable_ram_user();
- if (ram_user.user_id() != instance_ram_user.user_id()) {
- code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "ram user_id err";
- return;
- }
- std::string old_ak = instance_ram_user.ak();
- std::string old_sk = instance_ram_user.sk();
- if (old_ak == ak && old_sk == sk) {
- code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "ak sk eq original, please check it";
- return;
- }
- instance_ram_user.set_ak(std::move(cipher_ak_sk_pair.first));
- instance_ram_user.set_sk(std::move(cipher_ak_sk_pair.second));
- instance_ram_user.mutable_encryption_info()->CopyFrom(encryption_info);
- update_record << "update ram_user's ak sk, instance_id: " << instance_id
- << " user_id: " << ram_user.user_id() << " old: cipher ak: " << old_ak
- << " cipher sk: " << old_sk << " new: cipher ak: " << ak
- << " cipher sk: " << sk;
- }
-
- bool has_found_alter_obj_info = false;
- for (auto& alter_bucket_user : request->internal_bucket_user()) {
- if (!alter_bucket_user.has_ak() || !alter_bucket_user.has_sk() ||
- !alter_bucket_user.has_user_id()) {
- code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "s3 bucket info err " + proto_to_json(*request);
- return;
- }
- std::string user_id = alter_bucket_user.user_id();
- EncryptionInfoPB encryption_info;
- AkSkPair cipher_ak_sk_pair;
- if (encrypt_ak_sk_helper(alter_bucket_user.ak(), alter_bucket_user.sk(), &encryption_info,
- &cipher_ak_sk_pair, code, msg) != 0) {
- return;
- }
- const auto& [ak, sk] = cipher_ak_sk_pair;
- auto& obj_info =
- const_cast<std::decay_t<decltype(instance.obj_info())>&>(instance.obj_info());
- for (auto& it : obj_info) {
- std::string old_ak = it.ak();
- std::string old_sk = it.sk();
- if (!it.has_user_id()) {
- has_found_alter_obj_info = true;
- // For compatibility, obj_info without a user_id only allow
- // single internal_bucket_user to modify it.
- if (request->internal_bucket_user_size() != 1) {
- code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "fail to update old instance's obj_info, s3 obj info err " +
- proto_to_json(*request);
- return;
- }
- if (it.ak() == ak && it.sk() == sk) {
- code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "ak sk eq original, please check it";
- return;
- }
- it.set_mtime(time);
- it.set_user_id(user_id);
- it.set_ak(ak);
- it.set_sk(sk);
- it.mutable_encryption_info()->CopyFrom(encryption_info);
- update_record << "update obj_info's ak sk without user_id, instance_id: "
- << instance_id << " obj_info_id: " << it.id()
- << " new user_id: " << user_id << " old: cipher ak: " << old_ak
- << " cipher sk: " << old_sk << " new: cipher ak: " << ak
- << " cipher sk: " << sk;
- continue;
- }
- if (it.user_id() == user_id) {
- has_found_alter_obj_info = true;
- if (it.ak() == ak && it.sk() == sk) {
- code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "ak sk eq original, please check it";
- return;
- }
- it.set_mtime(time);
- it.set_ak(ak);
- it.set_sk(sk);
- it.mutable_encryption_info()->CopyFrom(encryption_info);
- update_record << "update obj_info's ak sk, instance_id: " << instance_id
- << " obj_info_id: " << it.id() << " user_id: " << user_id
- << " old: cipher ak: " << old_ak << " cipher sk: " << old_sk
- << " new: cipher ak: " << ak << " cipher sk: " << sk;
- }
- }
- }
-
- if (!request->internal_bucket_user().empty() && !has_found_alter_obj_info) {
- code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "fail to find the alter obj info";
+ // Update instance using helper function
+ if (update_instance_ak_sk(instance, request, time, code, msg, update_record) != 0) {
return;
}
@@ -1682,15 +1800,104 @@ void MetaServiceImpl::update_ak_sk(google::protobuf::RpcController* controller,
return;
}
+ txn->atomic_add(system_meta_service_instance_update_key(), 1);
txn->put(key, val);
LOG(INFO) << "put instance_id=" << instance_id << " instance_key=" << hex(key);
+
+ // Commit root instance first to avoid transaction timeout
err = txn->commit();
if (err != TxnErrorCode::TXN_OK) {
code = cast_as<ErrCategory::COMMIT>(err);
- msg = fmt::format("failed to commit kv txn, err={}", err);
+ msg = fmt::format("failed to commit root instance kv txn, err={}", err);
LOG(WARNING) << msg;
+ return;
}
+
LOG(INFO) << update_record.str();
+ async_notify_refresh_instance(txn_kv_, instance_id, true);
+
+ // Cascade update to derived instances using separate transactions
+ // update_ak_sk is idempotent, so it's safe to use independent transactions
+ if (!instance.has_snapshot_switch_status() ||
+ instance.snapshot_switch_status() == SNAPSHOT_SWITCH_DISABLED) {
+ LOG(INFO) << "snapshot disabled for instance_id=" << instance_id
+ << ", skip cascade updating derived instances";
+ return;
+ }
+
+ std::vector<std::string> cascade_instance_ids;
+ if (find_cascade_instances(txn_kv_.get(), instance_id, &cascade_instance_ids) != 0) {
+ LOG(WARNING) << "failed to find derived instances for cascade update, instance_id="
+ << instance_id << ", root instance already updated successfully";
+ return;
+ }
+
+ std::string cascade_ids_str;
+ for (size_t i = 0; i < cascade_instance_ids.size(); ++i) {
+ if (i > 0) cascade_ids_str += ", ";
+ cascade_ids_str += cascade_instance_ids[i];
+ }
+ LOG(INFO) << "Found " << cascade_instance_ids.size()
+ << " derived instances to cascade update: [" << cascade_ids_str << "]";
+
+ for (const auto& cascade_id : cascade_instance_ids) {
+ // Use a separate transaction for each derived instance
+ std::unique_ptr<Transaction> cascade_txn;
+ TxnErrorCode cascade_err = txn_kv_->create_txn(&cascade_txn);
+ if (cascade_err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to create txn for derived instance, instance_id=" << cascade_id
+ << " err=" << cascade_err;
+ continue;
+ }
+
+ InstanceKeyInfo cascade_key_info {cascade_id};
+ std::string cascade_key;
+ std::string cascade_val;
+ instance_key(cascade_key_info, &cascade_key);
+
+ cascade_err = cascade_txn->get(cascade_key, &cascade_val);
+ if (cascade_err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to get derived instance, instance_id=" << cascade_id
+ << " err=" << cascade_err;
+ continue;
+ }
+
+ InstanceInfoPB cascade_instance;
+ if (!cascade_instance.ParseFromString(cascade_val)) {
+ LOG(WARNING) << "failed to parse InstanceInfoPB for derived instance_id=" << cascade_id;
+ continue;
+ }
+
+ // Update the cascade instance using helper function
+ std::stringstream cascade_update_record;
+ MetaServiceCode cascade_code = MetaServiceCode::OK;
+ std::string cascade_msg;
+ if (update_instance_ak_sk(cascade_instance, request, time, cascade_code, cascade_msg,
+ cascade_update_record) != 0) {
+ LOG(WARNING) << "failed to update derived instance, instance_id=" << cascade_id
+ << " msg=" << cascade_msg;
+ continue;
+ }
+
+ cascade_val = cascade_instance.SerializeAsString();
+ if (cascade_val.empty()) {
+ LOG(WARNING) << "failed to serialize derived instance, instance_id=" << cascade_id;
+ continue;
+ }
+
+ cascade_txn->put(cascade_key, cascade_val);
+
+ cascade_err = cascade_txn->commit();
+ if (cascade_err != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "failed to commit derived instance txn, instance_id=" << cascade_id
+ << " err=" << cascade_err;
+ continue;
+ }
+
+ async_notify_refresh_instance(txn_kv_, cascade_id, true);
+ LOG(INFO) << "cascade update for instance_id=" << cascade_id << " "
+ << cascade_update_record.str();
+ }
}
void MetaServiceImpl::create_instance(google::protobuf::RpcController* controller,
@@ -1745,6 +1952,15 @@ void MetaServiceImpl::create_instance(google::protobuf::RpcController* controlle
new_ram_user.mutable_encryption_info()->CopyFrom(encryption_info);
instance.mutable_ram_user()->CopyFrom(new_ram_user);
}
+ if (config::enable_multi_version_status) {
+ instance.set_multi_version_status(MultiVersionStatus::MULTI_VERSION_READ_WRITE);
+ instance.set_snapshot_switch_status(SNAPSHOT_SWITCH_OFF);
+ if (config::enable_cluster_snapshot) {
+ instance.set_snapshot_switch_status(SNAPSHOT_SWITCH_ON);
+ instance.set_snapshot_interval_seconds(config::snapshot_min_interval_seconds);
+ instance.set_max_reserved_snapshot(1);
+ }
+ }
if (instance.instance_id().empty()) {
code = MetaServiceCode::INVALID_ARGUMENT;
@@ -1798,6 +2014,7 @@ void MetaServiceImpl::create_instance(google::protobuf::RpcController* controlle
return;
}
+ txn->atomic_add(system_meta_service_instance_update_key(), 1);
txn->put(key, val);
LOG(INFO) << "put instance_id=" << request->instance_id() << " instance_key=" << hex(key);
err = txn->commit();
@@ -1808,7 +2025,7 @@ void MetaServiceImpl::create_instance(google::protobuf::RpcController* controlle
}
async_notify_refresh_instance(
- txn_kv_, request->instance_id(),
+ txn_kv_, request->instance_id(), /*include_self=*/true,
[instance_id = request->instance_id()](const KVStats& stats) {
if (config::use_detailed_metrics && !instance_id.empty()) {
g_bvar_rpc_kv_create_instance_get_bytes.put({instance_id}, stats.get_bytes);
@@ -1818,54 +2035,79 @@ void MetaServiceImpl::create_instance(google::protobuf::RpcController* controlle
}
std::pair<MetaServiceCode, std::string> handle_snapshot_switch(const std::string& instance_id,
- const std::string& key,
const std::string& value,
InstanceInfoPB* instance) {
+ const std::string& property_name =
+ AlterInstanceRequest::SnapshotProperty_Name(AlterInstanceRequest::ENABLE_SNAPSHOT);
if (value != "true" && value != "false") {
return std::make_pair(MetaServiceCode::INVALID_ARGUMENT,
- "Invalid value for enabled property: " + value +
+ "Invalid value for " + property_name + " property: " + value +
", expected 'true' or 'false'" +
", instance_id: " + instance_id);
}
- if (instance->snapshot_switch_status() == SNAPSHOT_SWITCH_DISABLED) {
+
+ // Check if snapshot is not ready (UNSUPPORTED state)
+ if (!instance->has_snapshot_switch_status() ||
+ instance->snapshot_switch_status() == SNAPSHOT_SWITCH_DISABLED) {
return std::make_pair(MetaServiceCode::INVALID_ARGUMENT,
- "Snapshot not ready, instance_id: " + instance_id);
- }
- if (value == "true" && instance->snapshot_switch_status() == SNAPSHOT_SWITCH_ON) {
- return std::make_pair(
- MetaServiceCode::INVALID_ARGUMENT,
- "Snapshot is already set to SNAPSHOT_SWITCH_ON, instance_id: " + instance_id);
- }
- if (value == "false" && instance->snapshot_switch_status() == SNAPSHOT_SWITCH_OFF) {
+ "Snapshot is not ready, instance_id: " + instance_id);
+ } else if (value == "false" && instance->snapshot_switch_status() == SNAPSHOT_SWITCH_OFF) {
return std::make_pair(
MetaServiceCode::INVALID_ARGUMENT,
"Snapshot is already set to SNAPSHOT_SWITCH_OFF, instance_id: " + instance_id);
- }
- if (value == "true") {
+ } else if (value == "true" && instance->multi_version_status() != MULTI_VERSION_READ_WRITE) {
+ // If the multi_version_status is not READ_WRITE, cannot enable snapshot because the
+ // operation logs will be recycled directly since min_versionstamp is not set when multi
+ // version status is WRITE_ONLY
+ std::string url =
+ "${MS_ENDPOINT}/MetaService/http/"
+ "set_multi_version_status?multi_version_status=MULTI_VERSION_READ_WRITE";
+ return std::make_pair(MetaServiceCode::INVALID_ARGUMENT,
+ fmt::format("Cannot enable snapshot when multi_version_status is not "
+ "MULTI_VERSION_READ_WRITE. Consider enabling "
+ "MULTI_VERSION_READ_WRITE status by curl {}",
+ instance_id));
+ } else if (value == "true") {
instance->set_snapshot_switch_status(SNAPSHOT_SWITCH_ON);
+
+ // Set default values when first enabling snapshot
+ if (!instance->has_snapshot_interval_seconds() ||
+ instance->snapshot_interval_seconds() == 0) {
+ instance->set_snapshot_interval_seconds(config::snapshot_min_interval_seconds);
+ LOG(INFO) << "Set default snapshot_interval_seconds to "
+ << config::snapshot_min_interval_seconds << " for instance " << instance_id;
+ }
+ if (!instance->has_max_reserved_snapshot()) {
+ // Disable auto snapshot by default
+ instance->set_max_reserved_snapshot(0);
+ LOG(INFO) << "Set default max_reserved_snapshots to 0 for instance " << instance_id;
+ }
} else {
instance->set_snapshot_switch_status(SNAPSHOT_SWITCH_OFF);
}
- std::string msg = "Set snapshot enabled to " + value + " for instance " + instance_id;
- LOG(INFO) << msg;
+ LOG(INFO) << "Set snapshot " + property_name + " to " + value + " for instance " + instance_id;
return std::make_pair(MetaServiceCode::OK, "");
}
std::pair<MetaServiceCode, std::string> handle_max_reserved_snapshots(
- const std::string& instance_id, const std::string& key, const std::string& value,
- InstanceInfoPB* instance) {
+ const std::string& instance_id, const std::string& value, InstanceInfoPB* instance) {
+ const std::string& property_name = AlterInstanceRequest::SnapshotProperty_Name(
+ AlterInstanceRequest::MAX_RESERVED_SNAPSHOTS);
+
int max_snapshots;
try {
max_snapshots = std::stoi(value);
if (max_snapshots < 0) {
return std::make_pair(MetaServiceCode::INVALID_ARGUMENT,
- "max_reserved_snapshots must be non-negative, got: " + value);
+ property_name + " must be non-negative, got: " + value);
}
- if (max_snapshots > 35) {
+ if (max_snapshots > config::snapshot_max_reserved_num) {
return std::make_pair(MetaServiceCode::INVALID_ARGUMENT,
- "max_reserved_snapshots too large, maximum is 35, got: " + value);
+ property_name + " too large, maximum is " +
+ std::to_string(config::snapshot_max_reserved_num) +
+ ", got: " + value);
}
} catch (const std::exception& e) {
return std::make_pair(MetaServiceCode::INVALID_ARGUMENT,
@@ -1874,33 +2116,34 @@ std::pair<MetaServiceCode, std::string> handle_max_reserved_snapshots(
instance->set_max_reserved_snapshot(max_snapshots);
- std::string msg = "Set max_reserved_snapshots to " + value + " for instance " + instance_id;
- LOG(INFO) << msg;
+ LOG(INFO) << "Set " + property_name + " to " + value + " for instance " + instance_id;
return std::make_pair(MetaServiceCode::OK, "");
}
std::pair<MetaServiceCode, std::string> handle_snapshot_intervals(const std::string& instance_id,
- const std::string& key,
const std::string& value,
InstanceInfoPB* instance) {
+ const std::string& property_name = AlterInstanceRequest::SnapshotProperty_Name(
+ AlterInstanceRequest::SNAPSHOT_INTERVAL_SECONDS);
+
int intervals;
try {
intervals = std::stoi(value);
- if (intervals < 3600) {
- return std::make_pair(
- MetaServiceCode::INVALID_ARGUMENT,
- "snapshot_intervals too small, minimum is 3600 seconds, got: " + value);
+ if (intervals < config::snapshot_min_interval_seconds) {
+ return std::make_pair(MetaServiceCode::INVALID_ARGUMENT,
+ property_name + " too small, minimum is " +
+ std::to_string(config::snapshot_min_interval_seconds) +
+ " seconds, got: " + value);
}
} catch (const std::exception& e) {
return std::make_pair(MetaServiceCode::INVALID_ARGUMENT,
- "Invalid numeric value for snapshot_intervals: " + value);
+ "Invalid numeric value for " + property_name + ": " + value);
}
instance->set_snapshot_interval_seconds(intervals);
- std::string msg = "Set snapshot_intervals to " + value + " seconds for instance " + instance_id;
- LOG(INFO) << msg;
+ LOG(INFO) << "Set " + property_name + " to " + value + " seconds for instance " + instance_id;
return std::make_pair(MetaServiceCode::OK, "");
}
@@ -1932,32 +2175,68 @@ void MetaServiceImpl::alter_instance(google::protobuf::RpcController* controller
std::pair<MetaServiceCode, std::string> ret;
switch (request->op()) {
case AlterInstanceRequest::DROP: {
- ret = alter_instance(request, [&request](InstanceInfoPB* instance) {
- std::string msg;
- // check instance doesn't have any cluster.
- if (instance->clusters_size() != 0) {
- msg = "failed to drop instance, instance has clusters";
- LOG(WARNING) << msg;
- return std::make_pair(MetaServiceCode::INVALID_ARGUMENT, msg);
- }
+ ret = alter_instance(
+ request, [&request, &instance_id](Transaction* txn, InstanceInfoPB* instance) {
+ std::string msg;
+ // check instance doesn't have any cluster.
+ if (instance->clusters_size() != 0) {
+ msg = "failed to drop instance, instance has clusters";
+ LOG(WARNING) << msg;
+ return std::make_pair(MetaServiceCode::INVALID_ARGUMENT, msg);
+ }
- instance->set_status(InstanceInfoPB::DELETED);
- instance->set_mtime(
- duration_cast<seconds>(system_clock::now().time_since_epoch()).count());
+ // check instance doesn't have any snapshot.
+ MetaReader meta_reader(instance_id);
+ std::vector<std::pair<SnapshotPB, Versionstamp>> snapshots;
+ TxnErrorCode err = meta_reader.get_snapshots(txn, &snapshots);
+ if (err != TxnErrorCode::TXN_OK) {
+ msg = "failed to get snapshots";
+ LOG(WARNING) << msg << " err=" << err;
+ return std::make_pair(cast_as<ErrCategory::READ>(err), msg);
+ }
+ for (auto& [snapshot, _] : snapshots) {
+ if (snapshot.status() != SnapshotStatus::SNAPSHOT_RECYCLED) {
+ // still has snapshots, cannot drop
+ msg = "failed to drop instance, instance has snapshots";
+ LOG(WARNING) << msg;
+ return std::make_pair(MetaServiceCode::INVALID_ARGUMENT, msg);
+ }
+ }
- std::string ret = instance->SerializeAsString();
- if (ret.empty()) {
- msg = "failed to serialize";
- LOG(ERROR) << msg;
- return std::make_pair(MetaServiceCode::PROTOBUF_SERIALIZE_ERR, msg);
- }
- LOG(INFO) << "put instance_id=" << request->instance_id()
- << "drop instance json=" << proto_to_json(*instance);
- return std::make_pair(MetaServiceCode::OK, ret);
- });
+ instance->set_status(InstanceInfoPB::DELETED);
+ instance->set_mtime(
+ duration_cast<seconds>(system_clock::now().time_since_epoch()).count());
+
+ std::string ret = instance->SerializeAsString();
+ if (ret.empty()) {
+ msg = "failed to serialize";
+ LOG(ERROR) << msg;
+ return std::make_pair(MetaServiceCode::PROTOBUF_SERIALIZE_ERR, msg);
+ }
+ LOG(INFO) << "put instance_id=" << request->instance_id()
+ << "drop instance json=" << proto_to_json(*instance);
+
+ if (instance->has_source_instance_id() && instance->has_source_snapshot_id() &&
+ !instance->source_instance_id().empty() &&
+ !instance->source_snapshot_id().empty()) {
+ Versionstamp snapshot_versionstamp;
+ if (!SnapshotManager::parse_snapshot_versionstamp(
+ instance->source_snapshot_id(), &snapshot_versionstamp)) {
+ msg = "failed to parse snapshot_id to versionstamp, snapshot_id=" +
+ instance->source_snapshot_id();
+ LOG(WARNING) << msg;
+ return std::make_pair(MetaServiceCode::INVALID_ARGUMENT, msg);
+ }
+ versioned::SnapshotReferenceKeyInfo ref_key_info {
+ instance->source_instance_id(), snapshot_versionstamp, instance_id};
+ std::string reference_key = versioned::snapshot_reference_key(ref_key_info);
+ txn->remove(reference_key);
+ }
+ return std::make_pair(MetaServiceCode::OK, ret);
+ });
} break;
case AlterInstanceRequest::RENAME: {
- ret = alter_instance(request, [&request](InstanceInfoPB* instance) {
+ ret = alter_instance(request, [&request](Transaction* txn, InstanceInfoPB* instance) {
std::string msg;
std::string name = request->has_name() ? request->name() : "";
if (name.empty()) {
@@ -1979,7 +2258,7 @@ void MetaServiceImpl::alter_instance(google::protobuf::RpcController* controller
});
} break;
case AlterInstanceRequest::ENABLE_SSE: {
- ret = alter_instance(request, [&request](InstanceInfoPB* instance) {
+ ret = alter_instance(request, [&request](Transaction* txn, InstanceInfoPB* instance) {
std::string msg;
if (instance->sse_enabled()) {
msg = "failed to enable sse, instance has enabled sse";
@@ -2005,7 +2284,7 @@ void MetaServiceImpl::alter_instance(google::protobuf::RpcController* controller
});
} break;
case AlterInstanceRequest::DISABLE_SSE: {
- ret = alter_instance(request, [&request](InstanceInfoPB* instance) {
+ ret = alter_instance(request, [&request](Transaction* txn, InstanceInfoPB* instance) {
std::string msg;
if (!instance->sse_enabled()) {
msg = "failed to disable sse, instance has disabled sse";
@@ -2034,7 +2313,7 @@ void MetaServiceImpl::alter_instance(google::protobuf::RpcController* controller
ret = resource_mgr_->refresh_instance(request->instance_id());
} break;
case AlterInstanceRequest::SET_OVERDUE: {
- ret = alter_instance(request, [&request](InstanceInfoPB* instance) {
+ ret = alter_instance(request, [&request](Transaction* txn, InstanceInfoPB* instance) {
std::string msg;
if (instance->status() == InstanceInfoPB::DELETED) {
@@ -2065,7 +2344,7 @@ void MetaServiceImpl::alter_instance(google::protobuf::RpcController* controller
});
} break;
case AlterInstanceRequest::SET_NORMAL: {
- ret = alter_instance(request, [&request](InstanceInfoPB* instance) {
+ ret = alter_instance(request, [&request](Transaction* txn, InstanceInfoPB* instance) {
std::string msg;
if (instance->status() == InstanceInfoPB::DELETED) {
@@ -2096,56 +2375,59 @@ void MetaServiceImpl::alter_instance(google::protobuf::RpcController* controller
} break;
/**
* Handle SET_SNAPSHOT_PROPERTY operation - configures snapshot-related properties for an instance.
- *
+ *
* Supported property keys and their expected values:
- * - "enabled": "true" | "false"
+ * - "ENABLE_SNAPSHOT": "true" | "false"
* Controls whether snapshot functionality is enabled for the instance
- *
- * - "max_reserved_snapshots": numeric string (0-35)
+ *
+ * - "MAX_RESERVED_SNAPSHOTS": numeric string (0-config::snapshot_max_reserved_num)
* Sets the maximum number of snapshots to retain for the instance
- *
- * - "snapshot_intervals": numeric string (60-max)
- * Sets the snapshot creation interval in seconds (minimum 60s)
- *
+ *
+ * - "SNAPSHOT_INTERVAL_SECONDS": numeric string (config::snapshot_min_interval_seconds-max)
+ * Sets the snapshot creation interval in seconds (minimum controlled by config)
+ *
* Each property is validated by its respective handler function which ensures
* the provided values conform to the expected format and constraints.
*/
case AlterInstanceRequest::SET_SNAPSHOT_PROPERTY: {
- ret = alter_instance(request, [&request](InstanceInfoPB* instance) {
+ ret = alter_instance(request, [&request, &instance_id](Transaction* txn,
+ InstanceInfoPB* instance) {
std::string msg;
auto properties = request->properties();
if (properties.empty()) {
- msg = "propertiy is empty, instance_id = " + request->instance_id();
+ msg = "snapshot properties is empty, instance_id = " + request->instance_id();
LOG(WARNING) << msg;
return std::make_pair(MetaServiceCode::INVALID_ARGUMENT, msg);
}
for (const auto& property : properties) {
std::string key = property.first;
std::string value = property.second;
+ AlterInstanceRequest::SnapshotProperty snapshot_property =
+ AlterInstanceRequest::UNKNOWN_PROPERTY;
+ if (!AlterInstanceRequest_SnapshotProperty_Parse(key, &snapshot_property) ||
+ snapshot_property == AlterInstanceRequest::UNKNOWN_PROPERTY) {
+ msg = "unknown snapshot property: " + key;
+ LOG(WARNING) << "alter instance failed: " << msg
+ << ", instance_id = " << instance_id;
+ return std::make_pair(MetaServiceCode::INVALID_ARGUMENT, msg);
+ }
std::pair<MetaServiceCode, std::string> result;
- if (key == SNAPSHOT_ENABLED_KEY) {
- result = handle_snapshot_switch(request->instance_id(), key, value, instance);
- } else if (key == SNAPSHOT_MAX_RESERVED_KEY) {
- result = handle_max_reserved_snapshots(request->instance_id(), key, value,
- instance);
- } else if (key == SNAPSHOT_INTERVAL_SECONDS_KEY) {
- result =
- handle_snapshot_intervals(request->instance_id(), key, value, instance);
+ if (snapshot_property == AlterInstanceRequest::ENABLE_SNAPSHOT) {
+ result = handle_snapshot_switch(request->instance_id(), value, instance);
+ } else if (snapshot_property == AlterInstanceRequest::MAX_RESERVED_SNAPSHOTS) {
+ result = handle_max_reserved_snapshots(request->instance_id(), value, instance);
+ } else if (snapshot_property == AlterInstanceRequest::SNAPSHOT_INTERVAL_SECONDS) {
+ result = handle_snapshot_intervals(request->instance_id(), value, instance);
} else {
msg = "unsupported property: " + key;
- LOG(WARNING) << msg;
+ LOG(WARNING) << "alter instance failed: " << msg
+ << ", instance_id = " << instance_id;
return std::make_pair(MetaServiceCode::INVALID_ARGUMENT, msg);
}
- LOG(INFO) << "Property handling result for key=" << key
- << ", result_code=" << static_cast<int>(result.first)
- << ", result_msg=" << result.second;
-
if (result.first != MetaServiceCode::OK) {
- msg = result.second;
- LOG(WARNING) << msg;
return result;
}
}
@@ -2171,7 +2453,7 @@ void MetaServiceImpl::alter_instance(google::protobuf::RpcController* controller
if (request->op() == AlterInstanceRequest::REFRESH) return;
- async_notify_refresh_instance(txn_kv_, request->instance_id());
+ async_notify_refresh_instance(txn_kv_, request->instance_id(), /*include_self=*/false);
}
void MetaServiceImpl::get_instance(google::protobuf::RpcController* controller,
@@ -2228,7 +2510,8 @@ void MetaServiceImpl::get_instance(google::protobuf::RpcController* controller,
std::pair<MetaServiceCode, std::string> MetaServiceImpl::alter_instance(
const cloud::AlterInstanceRequest* request,
- std::function<std::pair<MetaServiceCode, std::string>(InstanceInfoPB*)> action) {
+ std::function<std::pair<MetaServiceCode, std::string>(Transaction*, InstanceInfoPB*)>
+ action) {
MetaServiceCode code = MetaServiceCode::OK;
std::string msg = "OK";
std::string instance_id = request->has_instance_id() ? request->instance_id() : "";
@@ -2272,11 +2555,12 @@ std::pair<MetaServiceCode, std::string> MetaServiceImpl::alter_instance(
LOG(WARNING) << msg;
return std::make_pair(code, msg);
}
- auto r = action(&instance);
+ auto r = action(txn.get(), &instance);
if (r.first != MetaServiceCode::OK) {
return r;
}
val = r.second;
+ txn->atomic_add(system_meta_service_instance_update_key(), 1);
txn->put(key, val);
err = txn->commit();
if (err != TxnErrorCode::TXN_OK) {
@@ -2826,7 +3110,7 @@ void MetaServiceImpl::alter_cluster(google::protobuf::RpcController* controller,
if (code != MetaServiceCode::OK) return;
async_notify_refresh_instance(
- txn_kv_, request->instance_id(),
+ txn_kv_, request->instance_id(), /*include_self=*/false,
[instance_id = request->instance_id()](const KVStats& stats) {
if (config::use_detailed_metrics && !instance_id.empty()) {
g_bvar_rpc_kv_alter_cluster_get_bytes.put({instance_id}, stats.get_bytes);
@@ -3156,6 +3440,7 @@ void MetaServiceImpl::create_stage(::google::protobuf::RpcController* controller
return;
}
+ txn->atomic_add(system_meta_service_instance_update_key(), 1);
txn->put(key, val);
LOG(INFO) << "put instance_id=" << instance_id << " instance_key=" << hex(key)
<< " json=" << proto_to_json(instance);
@@ -3546,6 +3831,7 @@ void MetaServiceImpl::drop_stage(google::protobuf::RpcController* controller,
txn->put(key1, val1);
}
+ txn->atomic_add(system_meta_service_instance_update_key(), 1);
err = txn->commit();
if (err != TxnErrorCode::TXN_OK) {
code = cast_as<ErrCategory::COMMIT>(err);
@@ -3813,6 +4099,7 @@ void MetaServiceImpl::alter_ram_user(google::protobuf::RpcController* controller
code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
return;
}
+ txn->atomic_add(system_meta_service_instance_update_key(), 1);
txn->put(key, val);
LOG(INFO) << "put instance_id=" << instance_id << " instance_key=" << hex(key);
err = txn->commit();
@@ -4312,8 +4599,14 @@ void MetaServiceImpl::get_cluster_status(google::protobuf::RpcController* contro
}
void notify_refresh_instance(std::shared_ptr<TxnKv> txn_kv, const std::string& instance_id,
- KVStats* stats) {
- LOG(INFO) << "begin notify_refresh_instance";
+ KVStats* stats, bool include_self) {
+ if (!config::enable_notify_instance_update) {
+ LOG(INFO) << "notify_refresh_instance is disabled";
+ return;
+ }
+
+ LOG(INFO) << "begin notify_refresh_instance, include_self=" << include_self;
+ TEST_SYNC_POINT_RETURN_WITH_VOID("notify_refresh_instance_return");
std::unique_ptr<Transaction> txn;
TxnErrorCode err = txn_kv->create_txn(&txn);
if (err != TxnErrorCode::TXN_OK) {
@@ -4357,7 +4650,7 @@ void notify_refresh_instance(std::shared_ptr<TxnKv> txn_kv, const std::string& i
} else {
endpoint = fmt::format("{}:{}", e.ip(), e.port());
}
- if (endpoint == self_endpoint) continue;
+ if (endpoint == self_endpoint && !include_self) continue;
// Prepare stub
std::shared_ptr<MetaService_Stub> stub;
diff --git a/cloud/src/meta-service/meta_service_snapshot.cpp b/cloud/src/meta-service/meta_service_snapshot.cpp
index 93ab49a342d..9dd86aac349 100644
--- a/cloud/src/meta-service/meta_service_snapshot.cpp
+++ b/cloud/src/meta-service/meta_service_snapshot.cpp
@@ -48,6 +48,30 @@ void MetaServiceImpl::begin_snapshot(::google::protobuf::RpcController* controll
msg = response->status().msg();
}
+void MetaServiceImpl::update_snapshot(::google::protobuf::RpcController* controller,
+ const UpdateSnapshotRequest* request,
+ UpdateSnapshotResponse* response,
+ ::google::protobuf::Closure* done) {
+ RPC_PREPROCESS(update_snapshot, get, put, del);
+ if (!request->has_cloud_unique_id() || request->cloud_unique_id().empty()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "cloud_unique_id not set";
+ return;
+ }
+
+ instance_id = get_instance_id(resource_mgr_, request->cloud_unique_id());
+ if (instance_id.empty()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "empty instance_id";
+ return;
+ }
+ RPC_RATE_LIMIT(update_snapshot);
+
+ snapshot_manager_->update_snapshot(instance_id, *request, response);
+ code = response->status().code();
+ msg = response->status().msg();
+}
+
void MetaServiceImpl::commit_snapshot(::google::protobuf::RpcController* controller,
const CommitSnapshotRequest* request,
CommitSnapshotResponse* response,
@@ -101,16 +125,20 @@ void MetaServiceImpl::list_snapshot(::google::protobuf::RpcController* controlle
ListSnapshotResponse* response,
::google::protobuf::Closure* done) {
RPC_PREPROCESS(list_snapshot, get, put, del);
- if (!request->has_cloud_unique_id() || request->cloud_unique_id().empty()) {
- code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "cloud_unique_id not set";
- return;
- }
- instance_id = get_instance_id(resource_mgr_, request->cloud_unique_id());
- if (instance_id.empty()) {
+ // Prefer instance_id if provided, fallback to cloud_unique_id
+ if (request->has_instance_id() && !request->instance_id().empty()) {
+ instance_id = request->instance_id();
+ } else if (request->has_cloud_unique_id() && !request->cloud_unique_id().empty()) {
+ instance_id = get_instance_id(resource_mgr_, request->cloud_unique_id());
+ if (instance_id.empty()) {
+ code = MetaServiceCode::INVALID_ARGUMENT;
+ msg = "empty instance_id";
+ return;
+ }
+ } else {
code = MetaServiceCode::INVALID_ARGUMENT;
- msg = "empty instance_id";
+ msg = "either instance_id or cloud_unique_id must be provided";
return;
}
RPC_RATE_LIMIT(list_snapshot);
diff --git a/cloud/src/meta-service/meta_service_tablet_stats.cpp b/cloud/src/meta-service/meta_service_tablet_stats.cpp
index b01e4f4ddb1..1b73efc2ba1 100644
--- a/cloud/src/meta-service/meta_service_tablet_stats.cpp
+++ b/cloud/src/meta-service/meta_service_tablet_stats.cpp
@@ -30,10 +30,12 @@
#include "common/util.h"
#include "meta-service/meta_service.h"
#include "meta-service/meta_service_helper.h"
-#include "meta-store/document_message.h"
+#include "meta-store/clone_chain_reader.h"
#include "meta-store/keys.h"
+#include "meta-store/meta_reader.h"
#include "meta-store/txn_kv.h"
#include "meta-store/txn_kv_error.h"
+#include "meta-store/versioned_value.h"
namespace doris::cloud {
@@ -169,6 +171,15 @@ void merge_tablet_stats(TabletStatsPB& stats, const TabletStats& detached_stats)
stats.set_segment_size(stats.segment_size() + detached_stats.segment_size);
}
+void detach_tablet_stats(const TabletStatsPB& stats, TabletStats& detached_stats) {
+ detached_stats.data_size = stats.data_size();
+ detached_stats.num_rows = stats.num_rows();
+ detached_stats.num_rowsets = stats.num_rowsets();
+ detached_stats.num_segs = stats.num_segments();
+ detached_stats.index_size = stats.index_size();
+ detached_stats.segment_size = stats.segment_size();
+}
+
void internal_get_tablet_stats(MetaServiceCode& code, std::string& msg, Transaction* txn,
const std::string& instance_id, const TabletIndexPB& idx,
TabletStatsPB& stats, bool snapshot) {
@@ -179,11 +190,10 @@ void internal_get_tablet_stats(MetaServiceCode& code, std::string& msg, Transact
}
}
-void internal_get_versioned_tablet_stats(MetaServiceCode& code, std::string& msg,
- MetaReader& meta_reader, Transaction* txn,
- const std::string& instance_id,
- const TabletIndexPB& tablet_idx, TabletStatsPB& stats,
- bool snapshot) {
+void internal_get_load_tablet_stats(MetaServiceCode& code, std::string& msg,
+ CloneChainReader& meta_reader, Transaction* txn,
+ const std::string& instance_id, const TabletIndexPB& tablet_idx,
+ TabletStatsPB& stats, bool snapshot) {
int64_t tablet_id = tablet_idx.tablet_id();
Versionstamp versionstamp;
@@ -192,7 +202,14 @@ void internal_get_versioned_tablet_stats(MetaServiceCode& code, std::string& msg
meta_reader.get_tablet_load_stats(txn, tablet_id, &stats, &versionstamp, snapshot);
if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
// If versioned stats doesn't exist, read from single version
- internal_get_tablet_stats(code, msg, txn, instance_id, tablet_idx, stats, snapshot);
+ TabletStatsPB compact_stats;
+ TabletStats detached_stats;
+ internal_get_tablet_stats(code, msg, txn, instance_id, tablet_idx, compact_stats,
+ detached_stats, snapshot);
+ if (code == MetaServiceCode::OK) {
+ // Only the detached stats are valid for load tablet stats.
+ merge_tablet_stats(stats, detached_stats);
+ }
} else if (err != TxnErrorCode::TXN_OK) {
code = cast_as<ErrCategory::READ>(err);
msg = fmt::format("failed to get versioned tablet stats, err={}", err);
@@ -201,9 +218,94 @@ void internal_get_versioned_tablet_stats(MetaServiceCode& code, std::string& msg
}
}
+void internal_get_load_tablet_stats_batch(
+ MetaServiceCode& code, std::string& msg, CloneChainReader& meta_reader, Transaction* txn,
+ const std::string& instance_id,
+ const std::unordered_map<int64_t, TabletIndexPB>& tablet_indexes,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats, bool snapshot) {
+ if (tablet_indexes.empty()) {
+ return;
+ }
+
+ // Collect all tablet_ids
+ std::vector<int64_t> tablet_ids;
+ tablet_ids.reserve(tablet_indexes.size());
+ for (const auto& [tablet_id, _] : tablet_indexes) {
+ tablet_ids.push_back(tablet_id);
+ }
+
+ // Batch get versioned tablet load stats
+ std::unordered_map<int64_t, TabletStatsPB> versioned_stats;
+ std::unordered_map<int64_t, Versionstamp> versionstamps;
+ TxnErrorCode err = meta_reader.get_tablet_load_stats(txn, tablet_ids, &versioned_stats,
+ &versionstamps, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ code = cast_as<ErrCategory::READ>(err);
+ msg = fmt::format("failed to batch get versioned tablet stats, err={}", err);
+ LOG(WARNING) << msg;
+ return;
+ }
+
+ // For tablets found in versioned stats, add them to output
+ for (const auto& [tablet_id, stats] : versioned_stats) {
+ (*tablet_stats)[tablet_id] = stats;
+ }
+
+ // For tablets not found in versioned stats, fall back to single version detached stats
+ std::vector<int64_t> fallback_tablet_ids;
+ for (int64_t tablet_id : tablet_ids) {
+ if (!versioned_stats.contains(tablet_id)) {
+ fallback_tablet_ids.push_back(tablet_id);
+ }
+ }
+
+ if (!fallback_tablet_ids.empty()) {
+ LOG(INFO) << "fallback to single version detached stats for " << fallback_tablet_ids.size()
+ << " tablets";
+
+ // Fall back to single version for each tablet
+ for (int64_t tablet_id : fallback_tablet_ids) {
+ auto it = tablet_indexes.find(tablet_id);
+ if (it == tablet_indexes.end()) {
+ continue;
+ }
+ const TabletIndexPB& tablet_idx = it->second;
+
+ TabletStatsPB compact_stats;
+ TabletStats detached_stats;
+ internal_get_tablet_stats(code, msg, txn, instance_id, tablet_idx, compact_stats,
+ detached_stats, snapshot);
+ if (code != MetaServiceCode::OK) {
+ LOG(WARNING) << "failed to get detached tablet stats for fallback, tablet_id="
+ << tablet_id << " code=" << code << " msg=" << msg;
+ return;
+ }
+
+ // Only the detached stats are valid for load tablet stats.
+ TabletStatsPB stats_pb;
+ merge_tablet_stats(stats_pb, detached_stats);
+ (*tablet_stats)[tablet_id] = std::move(stats_pb);
+ }
+ }
+}
+
+void internal_get_load_tablet_stats_batch(MetaServiceCode& code, std::string& msg,
+ CloneChainReader& meta_reader, Transaction* txn,
+ const std::string& instance_id,
+ const std::map<int64_t, TabletIndexPB>& tablet_indexes,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats,
+ bool snapshot) {
+ // Convert std::map to std::unordered_map and delegate to the main implementation
+ std::unordered_map<int64_t, TabletIndexPB> unordered_indexes(tablet_indexes.begin(),
+ tablet_indexes.end());
+ internal_get_load_tablet_stats_batch(code, msg, meta_reader, txn, instance_id,
+ unordered_indexes, tablet_stats, snapshot);
+}
+
MetaServiceResponseStatus parse_fix_tablet_stats_param(
std::shared_ptr<ResourceManager> resource_mgr, const std::string& table_id_str,
- const std::string& cloud_unique_id_str, int64_t& table_id, std::string& instance_id) {
+ const std::string& cloud_unique_id_str, const std::string& tablet_id_str, int64_t& table_id,
+ std::string& instance_id, int64_t& tablet_id) {
MetaServiceCode code = MetaServiceCode::OK;
std::string msg;
MetaServiceResponseStatus st;
@@ -218,6 +320,16 @@ MetaServiceResponseStatus parse_fix_tablet_stats_param(
return st;
}
+ if (!tablet_id_str.empty()) {
+ try {
+ tablet_id = std::stoll(tablet_id_str);
+ } catch (...) {
+ st.set_code(MetaServiceCode::INVALID_ARGUMENT);
+ st.set_msg("Invalid tablet_id, tablet_id: " + tablet_id_str);
+ return st;
+ }
+ }
+
instance_id = get_instance_id(resource_mgr, cloud_unique_id_str);
if (instance_id.empty()) {
code = MetaServiceCode::INVALID_ARGUMENT;
@@ -537,4 +649,163 @@ MetaServiceResponseStatus check_new_tablet_stats(
return st;
}
+std::pair<MetaServiceCode, std::string> fix_versioned_tablet_stats_internal(
+ TxnKv* txn_kv, const std::string& instance_id, const TabletIndexPB& tablet_idx,
+ bool is_versioned_read, bool is_versioned_write, ResourceManager* resource_mgr) {
+ int64_t tablet_id = tablet_idx.tablet_id();
+ std::unique_ptr<Transaction> txn;
+ MetaServiceCode code = MetaServiceCode::OK;
+ std::string msg;
+
+ TxnErrorCode err = txn_kv->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ code = cast_as<ErrCategory::CREATE>(err);
+ msg = "failed to create txn";
+ return {code, msg};
+ }
+
+ TabletStatsPB original_tablet_stat;
+ TabletStatsPB existing_compact_stats;
+ TabletStatsPB existing_load_stats;
+ Versionstamp compact_versionstamp;
+ Versionstamp load_versionstamp;
+ GetRowsetResponse resp;
+
+ CloneChainReader meta_reader(instance_id, resource_mgr);
+ if (is_versioned_read) {
+ // Get existing compact stats
+ err = meta_reader.get_tablet_compact_stats(txn.get(), tablet_id, &existing_compact_stats,
+ &compact_versionstamp, true);
+ if (err != TxnErrorCode::TXN_OK && err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ code = cast_as<ErrCategory::READ>(err);
+ msg = fmt::format("failed to get versioned compact stats, tablet_id={}, err={}",
+ tablet_id, err);
+ return {code, msg};
+ }
+
+ // Get existing load stats
+ err = meta_reader.get_tablet_load_stats(txn.get(), tablet_id, &existing_load_stats,
+ &load_versionstamp, true);
+ if (err != TxnErrorCode::TXN_OK && err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ code = cast_as<ErrCategory::READ>(err);
+ msg = fmt::format("failed to get versioned load stats, tablet_id={}, err={}", tablet_id,
+ err);
+ return {code, msg};
+ }
+ MetaReader::merge_tablet_stats(existing_compact_stats, existing_load_stats,
+ &original_tablet_stat);
+
+ std::vector<RowsetMetaCloudPB> rowset_metas;
+ int64_t start = 0, end = std::numeric_limits<int64_t>::max() - 1;
+ err = meta_reader.get_rowset_metas(txn.get(), tablet_id, start, end, &rowset_metas);
+ if (err != TxnErrorCode::TXN_OK) {
+ code = cast_as<ErrCategory::READ>(err);
+ msg = fmt::format("failed to get versioned rowset, err={}, tablet_id={}", err,
+ tablet_id);
+ return {code, msg};
+ }
+
+ std::move(rowset_metas.begin(), rowset_metas.end(),
+ google::protobuf::RepeatedPtrFieldBackInserter(resp.mutable_rowset_meta()));
+ } else {
+ internal_get_tablet_stats(code, msg, txn.get(), instance_id, tablet_idx,
+ original_tablet_stat, true);
+ if (code != MetaServiceCode::OK) {
+ return {code, msg};
+ }
+ // get rowsets in tablet and accumulate disk size
+ internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id,
+ tablet_id, code, msg, &resp);
+ if (code != MetaServiceCode::OK) {
+ return {code, msg};
+ }
+ }
+
+ int64_t table_id = original_tablet_stat.idx().table_id();
+ int64_t index_id = original_tablet_stat.idx().index_id();
+ int64_t partition_id = original_tablet_stat.idx().partition_id();
+
+ int64_t total_disk_size = 0;
+ int64_t index_disk_size = 0;
+ int64_t data_disk_size = 0;
+ for (const auto& rs_meta : resp.rowset_meta()) {
+ total_disk_size += rs_meta.total_disk_size();
+ index_disk_size += rs_meta.index_disk_size();
+ data_disk_size += rs_meta.data_disk_size();
+ }
+
+ // set new disk size to tabletPB and write it back
+ TabletStatsPB tablet_stat;
+ tablet_stat.CopyFrom(original_tablet_stat);
+ tablet_stat.set_data_size(total_disk_size);
+ tablet_stat.set_index_size(index_disk_size);
+ tablet_stat.set_segment_size(data_disk_size);
+
+ // Write single version stats
+ std::string tablet_stat_key;
+ std::string tablet_stat_value;
+ tablet_stat_key = stats_tablet_key({instance_id, table_id, index_id, partition_id, tablet_id});
+ if (!tablet_stat.SerializeToString(&tablet_stat_value)) {
+ code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
+ msg = "failed to serialize tablet stat";
+ return {code, msg};
+ }
+ txn->put(tablet_stat_key, tablet_stat_value);
+
+ std::string num_segs_key =
+ stats_tablet_num_segs_key({instance_id, table_id, index_id, partition_id, tablet_id});
+ std::string num_rows_key =
+ stats_tablet_num_rows_key({instance_id, table_id, index_id, partition_id, tablet_id});
+ std::string num_rowsets_key = stats_tablet_num_rowsets_key(
+ {instance_id, table_id, index_id, partition_id, tablet_id});
+ std::string data_size_key =
+ stats_tablet_data_size_key({instance_id, table_id, index_id, partition_id, tablet_id});
+ std::string index_size_key =
+ stats_tablet_index_size_key({instance_id, table_id, index_id, partition_id, tablet_id});
+ std::string segment_size_key = stats_tablet_segment_size_key(
+ {instance_id, table_id, index_id, partition_id, tablet_id});
+ txn->remove(num_segs_key);
+ txn->remove(num_rows_key);
+ txn->remove(num_rowsets_key);
+ txn->remove(data_size_key);
+ txn->remove(index_size_key);
+ txn->remove(segment_size_key);
+
+ if (is_versioned_write) {
+ // Write compact stats (aggregate stats with accurate disk sizes)
+ std::string compact_stats_key =
+ versioned::tablet_compact_stats_key({instance_id, tablet_id});
+ TabletStatsPB compact_stats = tablet_stat; // Use the fixed stats with accurate disk sizes
+ versioned_put(txn.get(), compact_stats_key, compact_versionstamp, tablet_stat_value);
+ LOG(INFO) << "put versioned tablet compact stats key=" << hex(compact_stats_key)
+ << " tablet_id=" << tablet_id << " with existing versionstamp";
+
+ // Write load stats (detached stats, set to 0 since we recalculated from rowsets)
+ std::string load_stats_key = versioned::tablet_load_stats_key({instance_id, tablet_id});
+ TabletStatsPB load_stats;
+ load_stats.mutable_idx()->CopyFrom(tablet_stat.idx());
+
+ std::string load_stats_value;
+ if (!load_stats.SerializeToString(&load_stats_value)) {
+ code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
+ msg = "failed to serialize load stats";
+ return {code, msg};
+ }
+
+ // Overwrite with existing versionstamp
+ versioned_put(txn.get(), load_stats_key, load_versionstamp, load_stats_value);
+ LOG(INFO) << "put versioned tablet load stats key=" << hex(load_stats_key)
+ << " tablet_id=" << tablet_id << " with existing versionstamp";
+ }
+
+ err = txn->commit();
+ if (err != TxnErrorCode::TXN_OK) {
+ code = cast_as<ErrCategory::COMMIT>(err);
+ msg = "failed to commit txn";
+ return {code, msg};
+ }
+
+ return {MetaServiceCode::OK, ""};
+}
+
} // namespace doris::cloud
diff --git a/cloud/src/meta-service/meta_service_tablet_stats.h b/cloud/src/meta-service/meta_service_tablet_stats.h
index 9624832cd16..177f0ab0200 100644
--- a/cloud/src/meta-service/meta_service_tablet_stats.h
+++ b/cloud/src/meta-service/meta_service_tablet_stats.h
@@ -19,7 +19,7 @@
#include <gen_cpp/cloud.pb.h>
-#include "meta-store/meta_reader.h"
+#include "meta-store/clone_chain_reader.h"
#include "resource-manager/resource_manager.h"
namespace doris::cloud {
@@ -47,18 +47,41 @@ void internal_get_tablet_stats(MetaServiceCode& code, std::string& msg, Transact
// Merge `detached_stats` `stats` to `stats`.
void merge_tablet_stats(TabletStatsPB& stats, const TabletStats& detached_stats);
+// Detach tablet stats from `stats` to `detached_stats`.
+void detach_tablet_stats(const TabletStatsPB& stats, TabletStats& detached_stats);
+
// Get merged tablet stats via `txn`. If an error occurs, `code` will be set to non OK.
void internal_get_tablet_stats(MetaServiceCode& code, std::string& msg, Transaction* txn,
const std::string& instance_id, const TabletIndexPB& idx,
TabletStatsPB& stats, bool snapshot = false);
-// Get versioned tablet stats via `txn`. If an error occurs, `code` will be set to non OK.
-// NOTE: this function returns original `TabletStatsPB` and detached tablet stats val stored in kv store,
-// MUST call `merge_tablet_stats(stats, detached_stats)` to get the real tablet stats.
-void internal_get_versioned_tablet_stats(MetaServiceCode& code, std::string& msg,
- MetaReader& meta_reader, Transaction* txn,
- const std::string& instance_id, const TabletIndexPB& idx,
- TabletStatsPB& stats, bool snapshot = false);
+// Get versioned load tablet stats via `txn`. If an error occurs, `code` will be set to non OK.
+//
+// If the versioned load stats doesn't exist, fall back to get single version detached tablet stats.
+void internal_get_load_tablet_stats(MetaServiceCode& code, std::string& msg,
+ CloneChainReader& meta_reader, Transaction* txn,
+ const std::string& instance_id, const TabletIndexPB& idx,
+ TabletStatsPB& stats, bool snapshot = false);
+
+// Batch version: Get versioned load tablet stats for multiple tablets via `txn`.
+// If an error occurs, `code` will be set to non OK.
+//
+// For tablets whose versioned load stats doesn't exist, fall back to get single version detached tablet stats.
+// tablet_indexes: map of tablet_id -> TabletIndexPB
+// tablet_stats: output map of tablet_id -> TabletStatsPB
+void internal_get_load_tablet_stats_batch(
+ MetaServiceCode& code, std::string& msg, CloneChainReader& meta_reader, Transaction* txn,
+ const std::string& instance_id,
+ const std::unordered_map<int64_t, TabletIndexPB>& tablet_indexes,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats, bool snapshot = false);
+
+// Overload for std::map
+void internal_get_load_tablet_stats_batch(MetaServiceCode& code, std::string& msg,
+ CloneChainReader& meta_reader, Transaction* txn,
+ const std::string& instance_id,
+ const std::map<int64_t, TabletIndexPB>& tablet_indexes,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats,
+ bool snapshot = false);
// clang-format off
/**
@@ -81,13 +104,18 @@ void internal_get_versioned_tablet_stats(MetaServiceCode& code, std::string& msg
MetaServiceResponseStatus parse_fix_tablet_stats_param(
std::shared_ptr<ResourceManager> resource_mgr, const std::string& table_id_str,
- const std::string& cloud_unique_id_str, int64_t& table_id, std::string& instance_id);
+ const std::string& cloud_unique_id_str, const std::string& tablet_id_str, int64_t& table_id,
+ std::string& instance_id, int64_t& tablet_id);
MetaServiceResponseStatus fix_tablet_stats_internal(
std::shared_ptr<TxnKv> txn_kv, std::pair<std::string, std::string>& key_pair,
std::vector<std::shared_ptr<TabletStatsPB>>& tablet_stat_shared_ptr_vec_batch,
const std::string& instance_id, size_t batch_size = 20);
+std::pair<MetaServiceCode, std::string> fix_versioned_tablet_stats_internal(
+ TxnKv* txn_kv, const std::string& instance_id, const TabletIndexPB& tablet_idx,
+ bool is_versioned_read, bool is_versioned_write, ResourceManager* resource_mgr);
+
MetaServiceResponseStatus check_new_tablet_stats(
std::shared_ptr<TxnKv> txn_kv, const std::string& instance_id,
const std::vector<std::shared_ptr<TabletStatsPB>>& tablet_stat_shared_ptr_vec_batch);
diff --git a/cloud/src/meta-service/meta_service_txn.cpp b/cloud/src/meta-service/meta_service_txn.cpp
index cf7ef31ba68..ca4877dd827 100644
--- a/cloud/src/meta-service/meta_service_txn.cpp
+++ b/cloud/src/meta-service/meta_service_txn.cpp
@@ -32,6 +32,8 @@
#include "meta-service/meta_service.h"
#include "meta-service/meta_service_helper.h"
#include "meta-service/meta_service_tablet_stats.h"
+#include "meta-store/blob_message.h"
+#include "meta-store/clone_chain_reader.h"
#include "meta-store/document_message.h"
#include "meta-store/keys.h"
#include "meta-store/meta_reader.h"
@@ -1505,7 +1507,7 @@ void MetaServiceImpl::commit_txn_immediately(
LOG(INFO) << "txn_id=" << txn_id << " txn_info=" << txn_info.ShortDebugString();
- MetaReader meta_reader(instance_id, txn_kv_.get());
+ CloneChainReader meta_reader(instance_id, resource_mgr_.get());
// Prepare rowset meta and new_versions
AnnotateTag txn_tag("txn_id", txn_id);
@@ -1660,6 +1662,20 @@ void MetaServiceImpl::commit_txn_immediately(
<< " rowset_size=" << rowset_size;
if (is_versioned_write) {
+ auto& rowset_meta = i.second;
+ std::string meta_rowset_key = versioned::meta_rowset_key(
+ {instance_id, tablet_id, rowset_meta.rowset_id_v2()});
+ if (config::enable_recycle_rowset_strip_key_bounds) {
+ doris::RowsetMetaCloudPB rowset_meta_copy = rowset_meta;
+ // Strip key bounds to shrink operation log for ts compaction recycle entries
+ rowset_meta_copy.clear_segments_key_bounds();
+ rowset_meta_copy.clear_segments_key_bounds_truncated();
+ blob_put(txn.get(), meta_rowset_key, rowset_meta_copy.SerializeAsString(), 0);
+ } else {
+ blob_put(txn.get(), meta_rowset_key, rowset_meta.SerializeAsString(), 0);
+ }
+ LOG(INFO) << "put versioned meta_rowset_key=" << hex(meta_rowset_key);
+
std::string versioned_rowset_key =
versioned::meta_rowset_load_key({instance_id, tablet_id, version});
RowsetMetaCloudPB copied_rowset_meta(i.second);
@@ -1768,6 +1784,20 @@ void MetaServiceImpl::commit_txn_immediately(
txn->put(info_key, info_val);
LOG(INFO) << "put info_key=" << hex(info_key) << " txn_id=" << txn_id;
+ // Batch get existing versioned tablet stats if needed
+ std::unordered_map<int64_t, TabletStatsPB> existing_versioned_stats;
+ if (is_versioned_write && !tablet_stats.empty()) {
+ internal_get_load_tablet_stats_batch(code, msg, meta_reader, txn.get(), instance_id,
+ tablet_ids, &existing_versioned_stats);
+ if (code != MetaServiceCode::OK) {
+ LOG(WARNING) << "batch get versioned tablet stats failed, code=" << code
+ << " msg=" << msg << " txn_id=" << txn_id;
+ return;
+ }
+ LOG(INFO) << "batch get " << existing_versioned_stats.size()
+ << " versioned tablet stats, txn_id=" << txn_id;
+ }
+
// Update stats of affected tablet
for (auto& [tablet_id, stats] : tablet_stats) {
DCHECK(tablet_ids.count(tablet_id));
@@ -1778,16 +1808,7 @@ void MetaServiceImpl::commit_txn_immediately(
if (code != MetaServiceCode::OK) return;
if (is_versioned_write) {
- TabletStatsPB stats_pb;
- internal_get_versioned_tablet_stats(code, msg, meta_reader, txn.get(), instance_id,
- tablet_idx, stats_pb);
- if (code != MetaServiceCode::OK) {
- LOG(WARNING) << "update versioned tablet stats failed, code=" << code
- << " msg=" << msg << " txn_id=" << txn_id
- << " tablet_id=" << tablet_id;
- return;
- }
-
+ TabletStatsPB stats_pb = existing_versioned_stats[tablet_id];
merge_tablet_stats(stats_pb, stats);
std::string stats_key = versioned::tablet_load_stats_key({instance_id, tablet_id});
if (!versioned::document_put(txn.get(), stats_key, std::move(stats_pb))) {
@@ -1810,7 +1831,6 @@ void MetaServiceImpl::commit_txn_immediately(
LOG(INFO) << "remove running_key=" << hex(running_key) << " txn_id=" << txn_id;
txn->remove(running_key);
- std::string recycle_key = recycle_txn_key({instance_id, db_id, txn_id});
RecycleTxnPB recycle_pb;
recycle_pb.set_creation_time(commit_time);
recycle_pb.set_label(txn_info.label());
@@ -1823,18 +1843,11 @@ void MetaServiceImpl::commit_txn_immediately(
operation_log.set_min_timestamp(meta_reader.min_read_version());
}
operation_log.mutable_commit_txn()->Swap(&commit_txn_log);
- std::string operation_log_value;
- if (!operation_log.SerializeToString(&operation_log_value)) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- ss << "failed to serialize operation_log, txn_id=" << txn_id;
- msg = ss.str();
- return;
- }
+ versioned::blob_put(txn.get(), log_key, operation_log);
LOG(INFO) << "put commit txn operation log, key=" << hex(log_key)
- << " txn_id=" << txn_id
- << " operation_log_size=" << operation_log_value.size();
- versioned_put(txn.get(), log_key, operation_log_value);
+ << " txn_id=" << txn_id;
} else {
+ std::string recycle_key = recycle_txn_key({instance_id, db_id, txn_id});
std::string recycle_val;
if (!recycle_pb.SerializeToString(&recycle_val)) {
code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
@@ -1843,6 +1856,8 @@ void MetaServiceImpl::commit_txn_immediately(
return;
}
txn->put(recycle_key, recycle_val);
+ LOG(INFO) << "xxx commit_txn put recycle_key key=" << hex(recycle_key)
+ << " txn_id=" << txn_id;
}
if (txn_info.load_job_source_type() ==
@@ -1860,8 +1875,6 @@ void MetaServiceImpl::commit_txn_immediately(
}
}
- LOG(INFO) << "xxx commit_txn put recycle_key key=" << hex(recycle_key)
- << " txn_id=" << txn_id;
LOG(INFO) << "commit_txn put_size=" << txn->put_bytes()
<< " del_size=" << txn->delete_bytes() << " num_put_keys=" << txn->num_put_keys()
<< " num_del_keys=" << txn->num_del_keys()
@@ -2050,7 +2063,7 @@ void MetaServiceImpl::commit_txn_eventually(
stats.del_counter += txn->num_del_keys();
};
- MetaReader meta_reader(instance_id, txn_kv_.get());
+ CloneChainReader meta_reader(instance_id, resource_mgr_.get());
AnnotateTag txn_tag("txn_id", txn_id);
@@ -2352,22 +2365,15 @@ void MetaServiceImpl::commit_txn_eventually(
operation_log.set_min_timestamp(meta_reader.min_read_version());
}
operation_log.mutable_commit_txn()->Swap(&commit_txn_log);
- std::string operation_log_value;
- if (!operation_log.SerializeToString(&operation_log_value)) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- ss << "failed to serialize operation_log, txn_id=" << txn_id;
- msg = ss.str();
- return;
- }
- versioned_put(txn.get(), log_key, operation_log_value);
+ versioned::blob_put(txn.get(), log_key, operation_log);
LOG(INFO) << "put commit txn operation log, key=" << hex(log_key)
- << " txn_id=" << txn_id << " log_size=" << operation_log_value.size();
+ << " txn_id=" << txn_id;
}
- VLOG_DEBUG << "put_size=" << txn->put_bytes() << " del_size=" << txn->delete_bytes()
- << " num_put_keys=" << txn->num_put_keys()
- << " num_del_keys=" << txn->num_del_keys()
- << " txn_size=" << txn->approximate_bytes() << " txn_id=" << txn_id;
+ LOG(INFO) << "put_size=" << txn->put_bytes() << " del_size=" << txn->delete_bytes()
+ << " num_put_keys=" << txn->num_put_keys()
+ << " num_del_keys=" << txn->num_del_keys()
+ << " txn_size=" << txn->approximate_bytes() << " txn_id=" << txn_id;
err = txn->commit();
if (err != TxnErrorCode::TXN_OK) {
@@ -2549,7 +2555,7 @@ void MetaServiceImpl::commit_txn_with_sub_txn(const CommitTxnRequest* request,
bool is_versioned_write = is_version_write_enabled(instance_id);
bool is_versioned_read = is_version_read_enabled(instance_id);
- MetaReader meta_reader(instance_id, txn_kv_.get());
+ CloneChainReader meta_reader(instance_id, resource_mgr_.get());
// Prepare rowset meta and new_versions
std::unordered_map<int64_t, TabletIndexPB> tablet_ids;
@@ -2713,6 +2719,20 @@ void MetaServiceImpl::commit_txn_with_sub_txn(const CommitTxnRequest* request,
<< " rowset_size=" << rowset_size;
if (is_versioned_write) {
+ auto& rowset_meta = i.second;
+ std::string meta_rowset_key = versioned::meta_rowset_key(
+ {instance_id, rowset_meta.tablet_id(), rowset_meta.rowset_id_v2()});
+ if (config::enable_recycle_rowset_strip_key_bounds) {
+ doris::RowsetMetaCloudPB rowset_meta_copy = rowset_meta;
+ // Strip key bounds to shrink operation log for ts compaction recycle entries
+ rowset_meta_copy.clear_segments_key_bounds();
+ rowset_meta_copy.clear_segments_key_bounds_truncated();
+ blob_put(txn.get(), meta_rowset_key, rowset_meta_copy.SerializeAsString(), 0);
+ } else {
+ blob_put(txn.get(), meta_rowset_key, rowset_meta.SerializeAsString(), 0);
+ }
+ LOG(INFO) << "put versioned meta_rowset_key=" << hex(meta_rowset_key);
+
std::string versioned_rowset_key =
versioned::meta_rowset_load_key({instance_id, tablet_id, version});
if (!versioned::document_put(txn.get(), versioned_rowset_key,
@@ -2816,6 +2836,20 @@ void MetaServiceImpl::commit_txn_with_sub_txn(const CommitTxnRequest* request,
txn->put(info_key, info_val);
LOG(INFO) << "xxx put info_key=" << hex(info_key) << " txn_id=" << txn_id;
+ // Batch get existing versioned tablet stats if needed
+ std::unordered_map<int64_t, TabletStatsPB> existing_versioned_stats;
+ if (is_versioned_write && !tablet_stats.empty()) {
+ internal_get_load_tablet_stats_batch(code, msg, meta_reader, txn.get(), instance_id,
+ tablet_ids, &existing_versioned_stats);
+ if (code != MetaServiceCode::OK) {
+ LOG(WARNING) << "batch get versioned tablet stats failed, code=" << code
+ << " msg=" << msg << " txn_id=" << txn_id;
+ return;
+ }
+ LOG(INFO) << "batch get " << existing_versioned_stats.size()
+ << " versioned tablet stats, txn_id=" << txn_id;
+ }
+
// Update stats of affected tablet
for (auto& [tablet_id, stats] : tablet_stats) {
DCHECK(tablet_ids.count(tablet_id));
@@ -2826,16 +2860,7 @@ void MetaServiceImpl::commit_txn_with_sub_txn(const CommitTxnRequest* request,
if (code != MetaServiceCode::OK) return;
if (is_versioned_write) {
- TabletStatsPB stats_pb;
- internal_get_versioned_tablet_stats(code, msg, meta_reader, txn.get(), instance_id,
- tablet_idx, stats_pb);
- if (code != MetaServiceCode::OK) {
- LOG(WARNING) << "update versioned tablet stats failed, code=" << code
- << " msg=" << msg << " txn_id=" << txn_id
- << " tablet_id=" << tablet_id;
- return;
- }
-
+ TabletStatsPB stats_pb = existing_versioned_stats[tablet_id];
merge_tablet_stats(stats_pb, stats);
std::string stats_key = versioned::tablet_load_stats_key({instance_id, tablet_id});
if (!versioned::document_put(txn.get(), stats_key, std::move(stats_pb))) {
@@ -2869,21 +2894,14 @@ void MetaServiceImpl::commit_txn_with_sub_txn(const CommitTxnRequest* request,
if (is_versioned_write) {
commit_txn_log.mutable_recycle_txn()->Swap(&recycle_pb);
std::string log_key = versioned::log_key({instance_id});
- std::string operation_log_value;
OperationLogPB operation_log;
if (is_versioned_read) {
operation_log.set_min_timestamp(meta_reader.min_read_version());
}
operation_log.mutable_commit_txn()->Swap(&commit_txn_log);
- if (!operation_log.SerializeToString(&operation_log_value)) {
- code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- ss << "failed to serialize operation_log, txn_id=" << txn_id;
- msg = ss.str();
- return;
- }
- versioned_put(txn.get(), log_key, operation_log_value);
+ versioned::blob_put(txn.get(), log_key, operation_log);
LOG(INFO) << "put commit txn operation log key=" << hex(recycle_key)
- << " txn_id=" << txn_id << " log_size=" << operation_log_value.size();
+ << " txn_id=" << txn_id;
} else {
if (!recycle_pb.SerializeToString(&recycle_val)) {
code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
@@ -4085,58 +4103,89 @@ TxnErrorCode internal_clean_label(std::shared_ptr<TxnKv> txn_kv, const std::stri
const std::string index_key = txn_index_key({instance_id, txn_id});
const std::string info_key = txn_info_key({instance_id, db_id, txn_id});
- std::string info_val;
- err = txn->get(info_key, &info_val);
- if (err != TxnErrorCode::TXN_OK) {
- LOG_WARNING("info_key get failed")
- .tag("info_key", hex(info_key))
- .tag("label_key", hex(label_key))
- .tag("db_id", db_id)
- .tag("txn_id", txn_id)
- .tag("err", err);
- return err;
- }
+ if (is_versioned_write) {
+ // In versioned write mode, recycle_txn_key is written only when commit_txn_log is recycled.
+ // Use recycle_txn_key existence as the gate to avoid deleting txn_info before recycler reads it.
+ std::string recycle_val;
+ TxnErrorCode recycle_err = txn->get(recycle_key, &recycle_val);
+ if (recycle_err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ survival_txn_ids.push_back(txn_id);
+ LOG(INFO) << "versioned write mode, recycle_key not found, skip"
+ << " label_key=" << hex(label_key) << " txn_id=" << txn_id;
+ continue;
+ } else if (recycle_err != TxnErrorCode::TXN_OK) {
+ LOG_WARNING("failed to get recycle_key")
+ .tag("recycle_key", hex(recycle_key))
+ .tag("label_key", hex(label_key))
+ .tag("db_id", db_id)
+ .tag("txn_id", txn_id)
+ .tag("err", recycle_err);
+ return recycle_err;
+ }
- TxnInfoPB txn_info;
- if (!txn_info.ParseFromString(info_val)) {
- LOG_WARNING("info_val parse failed")
- .tag("info_key", hex(info_key))
- .tag("label_key", hex(label_key))
- .tag("db_id", db_id)
- .tag("txn_id", txn_id)
- .tag("size", info_val.size());
- return TxnErrorCode::TXN_UNIDENTIFIED_ERROR;
- }
+ txn->remove(index_key);
+ key_size += index_key.size();
- std::string recycle_val;
- if ((txn_info.status() != TxnStatusPB::TXN_STATUS_ABORTED) &&
- (txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE)) {
- // txn status is not final status
- LOG(INFO) << "txn not final state, label_key=" << hex(label_key)
- << " txn_id=" << txn_id;
- survival_txn_ids.push_back(txn_id);
- DCHECK_EQ(txn->get(recycle_key, &recycle_val), TxnErrorCode::TXN_KEY_NOT_FOUND);
- continue;
- }
+ txn->remove(info_key);
+ key_size += info_key.size();
+
+ txn->remove(recycle_key);
+ key_size += recycle_key.size();
+ clean_txn_ids.push_back(txn_id);
+ LOG(INFO) << "versioned write mode, remove index_key=" << hex(index_key)
+ << " info_key=" << hex(info_key) << " recycle_key=" << hex(recycle_key);
+ } else {
+ // Single version mode: check txn_info status before cleaning
+ std::string info_val;
+ err = txn->get(info_key, &info_val);
+ if (err != TxnErrorCode::TXN_OK) {
+ LOG_WARNING("info_key get failed")
+ .tag("info_key", hex(info_key))
+ .tag("label_key", hex(label_key))
+ .tag("db_id", db_id)
+ .tag("txn_id", txn_id)
+ .tag("err", err);
+ return err;
+ }
+
+ TxnInfoPB txn_info;
+ if (!txn_info.ParseFromString(info_val)) {
+ LOG_WARNING("info_val parse failed")
+ .tag("info_key", hex(info_key))
+ .tag("label_key", hex(label_key))
+ .tag("db_id", db_id)
+ .tag("txn_id", txn_id)
+ .tag("size", info_val.size());
+ return TxnErrorCode::TXN_UNIDENTIFIED_ERROR;
+ }
+
+ std::string recycle_val;
+ if ((txn_info.status() != TxnStatusPB::TXN_STATUS_ABORTED) &&
+ (txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE)) {
+ // txn status is not final status
+ LOG(INFO) << "txn not final state, label_key=" << hex(label_key)
+ << " txn_id=" << txn_id;
+ survival_txn_ids.push_back(txn_id);
+ DCHECK_EQ(txn->get(recycle_key, &recycle_val), TxnErrorCode::TXN_KEY_NOT_FOUND);
+ continue;
+ }
- // In versioned write, the recycle key will be write only when the txn operation log is recycled.
- if (!is_versioned_write) {
DCHECK_EQ(txn->get(recycle_key, &recycle_val), TxnErrorCode::TXN_OK);
- }
- DCHECK((txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) ||
- (txn_info.status() == TxnStatusPB::TXN_STATUS_VISIBLE));
+ DCHECK((txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) ||
+ (txn_info.status() == TxnStatusPB::TXN_STATUS_VISIBLE));
- txn->remove(index_key);
- key_size += index_key.size();
+ txn->remove(index_key);
+ key_size += index_key.size();
- txn->remove(info_key);
- key_size += info_key.size();
+ txn->remove(info_key);
+ key_size += info_key.size();
- txn->remove(recycle_key);
- key_size += recycle_key.size();
- clean_txn_ids.push_back(txn_id);
- LOG(INFO) << "remove index_key=" << hex(index_key) << " info_key=" << hex(info_key)
- << " recycle_key=" << hex(recycle_key);
+ txn->remove(recycle_key);
+ key_size += recycle_key.size();
+ clean_txn_ids.push_back(txn_id);
+ LOG(INFO) << "remove index_key=" << hex(index_key) << " info_key=" << hex(info_key)
+ << " recycle_key=" << hex(recycle_key);
+ }
}
if (label_pb.txn_ids().size() == clean_txn_ids.size()) {
txn->remove(label_key);
diff --git a/cloud/src/meta-service/txn_lazy_committer.cpp b/cloud/src/meta-service/txn_lazy_committer.cpp
index ddf0cd111e6..9edf21a8a1a 100644
--- a/cloud/src/meta-service/txn_lazy_committer.cpp
+++ b/cloud/src/meta-service/txn_lazy_committer.cpp
@@ -20,20 +20,27 @@
#include <gen_cpp/cloud.pb.h>
#include <gen_cpp/olap_file.pb.h>
+#include <cerrno>
#include <chrono>
+#include <random>
+#include "common/bvars.h"
+#include "common/config.h"
#include "common/defer.h"
#include "common/logging.h"
#include "common/stats.h"
+#include "common/sync_executor.h"
#include "common/util.h"
#include "cpp/sync_point.h"
#include "meta-service/meta_service_helper.h"
#include "meta-service/meta_service_tablet_stats.h"
+#include "meta-store/blob_message.h"
+#include "meta-store/clone_chain_reader.h"
#include "meta-store/document_message.h"
#include "meta-store/keys.h"
-#include "meta-store/meta_reader.h"
#include "meta-store/txn_kv_error.h"
#include "meta-store/versioned_value.h"
+#include "resource-manager/resource_manager.h"
using namespace std::chrono;
@@ -52,51 +59,73 @@ void update_tablet_stats(const StatsTabletKeyInfo& info, const TabletStats& stat
std::unique_ptr<Transaction>& txn, MetaServiceCode& code,
std::string& msg);
-// Get the versionstamp from the partition version key.
-//
-// The partition version key is constructed during the txn commit process, so the versionstamp
-// can be retrieved from the key itself.
-//
-// In order to keep consistency, the pending_txn_id is used to ensure the correct versionstamp
-// is returned. The is_partition_version_valid flag indicates whether the above condition is met.
-std::pair<MetaServiceCode, std::string> get_partition_versionstamp(
- TxnKv* txn_kv, std::string_view instance_id, int64_t txn_id, int64_t partition_id,
- Versionstamp* versionstamp, bool* is_partition_version_valid) {
- std::string partition_key = versioned::partition_version_key({instance_id, partition_id});
-
- std::unique_ptr<Transaction> txn;
- TxnErrorCode err = txn_kv->create_txn(&txn);
- if (err != TxnErrorCode::TXN_OK) {
- return {cast_as<ErrCategory::CREATE>(err),
- fmt::format("failed to create txn, txn_id={}, err={}", txn_id, err)};
+static uint64_t generate_unique_seed() {
+ if (config::txn_lazy_commit_shuffle_seed != 0) {
+ return config::txn_lazy_commit_shuffle_seed;
+ } else {
+ auto now = high_resolution_clock::now();
+ return duration_cast<nanoseconds>(now.time_since_epoch()).count();
}
+}
- std::string partition_version_value;
- err = versioned_get(txn.get(), partition_key, versionstamp, &partition_version_value);
- if (err != TxnErrorCode::TXN_OK) {
- MetaServiceCode code = err == TxnErrorCode::TXN_KEY_NOT_FOUND
- ? MetaServiceCode::TXN_ID_NOT_FOUND
- : cast_as<ErrCategory::READ>(err);
- return {code, fmt::format("failed to get partition version, txn_id={}, key={} err={}",
- txn_id, hex(partition_key), err)};
- }
+// Get the partition version from the txn kv store.
+// If is_versioned_read is true, use versioned get to read the partition version with versionstamp.
+static std::pair<MetaServiceCode, std::string> get_partition_version(
+ Transaction* txn, std::string_view instance_id, int64_t txn_id, int64_t db_id,
+ int64_t table_id, int64_t partition_id, VersionPB* partition_version,
+ Versionstamp* versionstamp, bool is_versioned_read) {
+ std::string partition_key, partition_version_value;
+ if (is_versioned_read) {
+ partition_key = versioned::partition_version_key({instance_id, partition_id});
+ TxnErrorCode err =
+ versioned_get(txn, partition_key, versionstamp, &partition_version_value);
+ if (err != TxnErrorCode::TXN_OK) {
+ MetaServiceCode code = err == TxnErrorCode::TXN_KEY_NOT_FOUND
+ ? MetaServiceCode::TXN_ID_NOT_FOUND
+ : cast_as<ErrCategory::READ>(err);
+ return {code, fmt::format("failed to get partition version, txn_id={}, key={} err={}",
+ txn_id, hex(partition_key), err)};
+ }
- VersionPB partition_version;
- if (!partition_version.ParseFromString(partition_version_value)) {
+ } else {
+ partition_key = partition_version_key({instance_id, db_id, table_id, partition_id});
+ TxnErrorCode err = txn->get(partition_key, &partition_version_value);
+ if (err != TxnErrorCode::TXN_OK) {
+ MetaServiceCode code = cast_as<ErrCategory::READ>(err);
+ return {code,
+ fmt::format("failed to get partition version, txn_id={}, key={} err={}, "
+ "db_id={}, table_id={}, partition_id={}",
+ txn_id, hex(partition_key), err, db_id, table_id, partition_id)};
+ }
+ }
+ if (!partition_version->ParseFromString(partition_version_value)) {
return {MetaServiceCode::PROTOBUF_PARSE_ERR,
fmt::format("failed to parse partition version pb, txn_id={}, key={}", txn_id,
hex(partition_key))};
}
- *is_partition_version_valid = partition_version.pending_txn_ids_size() > 0 &&
- partition_version.pending_txn_ids(0) == txn_id;
-
return {MetaServiceCode::OK, ""};
}
-std::pair<MetaServiceCode, std::string> get_txn_info(TxnKv* txn_kv, const std::string& instance_id,
- int64_t db_id, int64_t txn_id,
- TxnInfoPB* txn_info) {
+static std::pair<MetaServiceCode, std::string> get_partition_version(
+ TxnKv* txn_kv, std::string_view instance_id, int64_t txn_id, int64_t db_id,
+ int64_t table_id, int64_t partition_id, VersionPB* partition_version,
+ Versionstamp* versionstamp, bool is_versioned_read) {
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return {cast_as<ErrCategory::CREATE>(err),
+ fmt::format("failed to create txn, txn_id={}, err={}", txn_id, err)};
+ }
+
+ return get_partition_version(txn.get(), instance_id, txn_id, db_id, table_id, partition_id,
+ partition_version, versionstamp, is_versioned_read);
+}
+
+static std::pair<MetaServiceCode, std::string> get_txn_info(TxnKv* txn_kv,
+ const std::string& instance_id,
+ int64_t db_id, int64_t txn_id,
+ TxnInfoPB* txn_info) {
std::string info_key = txn_info_key({instance_id, db_id, txn_id});
std::string info_value;
@@ -123,12 +152,68 @@ std::pair<MetaServiceCode, std::string> get_txn_info(TxnKv* txn_kv, const std::s
return {MetaServiceCode::OK, ""};
}
+static std::pair<MetaServiceCode, std::string> get_tablet_index(
+ CloneChainReader& meta_reader, Transaction* txn, std::string_view instance_id,
+ int64_t txn_id, int64_t tablet_id, TabletIndexPB* tablet_idx, bool is_versioned_read) {
+ std::stringstream ss;
+ MetaServiceCode code = MetaServiceCode::OK;
+ std::string msg;
+
+ if (!is_versioned_read) {
+ std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
+ std::string tablet_idx_val;
+ TxnErrorCode err = txn->get(tablet_idx_key, &tablet_idx_val, true);
+ if (TxnErrorCode::TXN_OK != err) {
+ code = err == TxnErrorCode::TXN_KEY_NOT_FOUND ? MetaServiceCode::TXN_ID_NOT_FOUND
+ : cast_as<ErrCategory::READ>(err);
+ ss << "failed to get tablet idx, txn_id=" << txn_id << " key=" << hex(tablet_idx_key)
+ << " err=" << err;
+ msg = ss.str();
+ LOG(WARNING) << msg;
+ return {code, msg};
+ }
+
+ if (!tablet_idx->ParseFromString(tablet_idx_val)) {
+ code = MetaServiceCode::PROTOBUF_PARSE_ERR;
+ ss << "failed to parse tablet idx pb txn_id=" << txn_id
+ << " key=" << hex(tablet_idx_key);
+ msg = ss.str();
+ return {code, msg};
+ }
+ } else {
+ TxnErrorCode err = meta_reader.get_tablet_index(txn, tablet_id, tablet_idx);
+ if (err != TxnErrorCode::TXN_OK) {
+ code = err == TxnErrorCode::TXN_KEY_NOT_FOUND ? MetaServiceCode::TXN_ID_NOT_FOUND
+ : cast_as<ErrCategory::READ>(err);
+ ss << "failed to get tablet index, txn_id=" << txn_id << " tablet_id=" << tablet_id
+ << " err=" << err;
+ msg = ss.str();
+ LOG(WARNING) << msg;
+ return {code, msg};
+ }
+ }
+ return {code, msg};
+}
+
+static std::pair<MetaServiceCode, std::string> get_tablet_index(
+ CloneChainReader& meta_reader, TxnKv* txn_kv, std::string_view instance_id, int64_t txn_id,
+ int64_t tablet_id, TabletIndexPB* tablet_idx, bool is_versioned_read) {
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return {cast_as<ErrCategory::CREATE>(err),
+ fmt::format("failed to create txn, txn_id={}, err={}", txn_id, err)};
+ }
+ return get_tablet_index(meta_reader, txn.get(), instance_id, txn_id, tablet_id, tablet_idx,
+ is_versioned_read);
+}
+
void convert_tmp_rowsets(
const std::string& instance_id, int64_t txn_id, std::shared_ptr<TxnKv> txn_kv,
MetaServiceCode& code, std::string& msg, int64_t db_id,
std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>& tmp_rowsets_meta,
std::map<int64_t, TabletIndexPB>& tablet_ids, bool is_versioned_write,
- bool is_versioned_read, Versionstamp versionstamp) {
+ bool is_versioned_read, Versionstamp versionstamp, ResourceManager* resource_mgr) {
std::stringstream ss;
std::unique_ptr<Transaction> txn;
TxnErrorCode err = txn_kv->create_txn(&txn);
@@ -140,7 +225,7 @@ void convert_tmp_rowsets(
return;
}
- MetaReader meta_reader(instance_id, txn_kv.get());
+ CloneChainReader meta_reader(instance_id, txn_kv.get(), resource_mgr);
// partition_id -> VersionPB
std::unordered_map<int64_t, VersionPB> partition_versions;
@@ -170,42 +255,11 @@ void convert_tmp_rowsets(
if (!tablet_ids.contains(tmp_rowset_pb.tablet_id())) {
TabletIndexPB tablet_idx_pb;
- if (!is_versioned_read) {
- std::string tablet_idx_key =
- meta_tablet_idx_key({instance_id, tmp_rowset_pb.tablet_id()});
- std::string tablet_idx_val;
- err = txn->get(tablet_idx_key, &tablet_idx_val, true);
- if (TxnErrorCode::TXN_OK != err) {
- code = err == TxnErrorCode::TXN_KEY_NOT_FOUND
- ? MetaServiceCode::TXN_ID_NOT_FOUND
- : cast_as<ErrCategory::READ>(err);
- ss << "failed to get tablet idx, txn_id=" << txn_id
- << " key=" << hex(tablet_idx_key) << " err=" << err;
- msg = ss.str();
- LOG(WARNING) << msg;
- return;
- }
-
- if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
- code = MetaServiceCode::PROTOBUF_PARSE_ERR;
- ss << "failed to parse tablet idx pb txn_id=" << txn_id
- << " key=" << hex(tablet_idx_key);
- msg = ss.str();
- return;
- }
- } else {
- err = meta_reader.get_tablet_index(txn.get(), tmp_rowset_pb.tablet_id(),
- &tablet_idx_pb);
- if (err != TxnErrorCode::TXN_OK) {
- code = err == TxnErrorCode::TXN_KEY_NOT_FOUND
- ? MetaServiceCode::TXN_ID_NOT_FOUND
- : cast_as<ErrCategory::READ>(err);
- ss << "failed to get tablet index, txn_id=" << txn_id
- << " tablet_id=" << tmp_rowset_pb.tablet_id() << " err=" << err;
- msg = ss.str();
- LOG(WARNING) << msg;
- return;
- }
+ std::tie(code, msg) =
+ get_tablet_index(meta_reader, txn.get(), instance_id, txn_id,
+ tmp_rowset_pb.tablet_id(), &tablet_idx_pb, is_versioned_read);
+ if (code != MetaServiceCode::OK) {
+ return;
}
tablet_ids.emplace(tmp_rowset_pb.tablet_id(), tablet_idx_pb);
}
@@ -337,6 +391,19 @@ void convert_tmp_rowsets(
stats.segment_size += tmp_rowset_pb.data_disk_size();
if (is_versioned_write) {
+ std::string meta_rowset_key = versioned::meta_rowset_key(
+ {instance_id, tmp_rowset_pb.tablet_id(), tmp_rowset_pb.rowset_id_v2()});
+ if (config::enable_recycle_rowset_strip_key_bounds) {
+ doris::RowsetMetaCloudPB rowset_meta_copy = tmp_rowset_pb;
+ // Strip key bounds to shrink operation log for ts compaction recycle entries
+ rowset_meta_copy.clear_segments_key_bounds();
+ rowset_meta_copy.clear_segments_key_bounds_truncated();
+ blob_put(txn.get(), meta_rowset_key, rowset_meta_copy.SerializeAsString(), 0);
+ } else {
+ blob_put(txn.get(), meta_rowset_key, tmp_rowset_pb.SerializeAsString(), 0);
+ }
+ LOG(INFO) << "put versioned meta_rowset_key=" << hex(meta_rowset_key);
+
// If this is a versioned write, we need to put the rowset with versionstamp
RowsetMetaCloudPB copied_rowset_meta(tmp_rowset_pb);
std::string rowset_load_key = versioned::meta_rowset_load_key(
@@ -354,6 +421,20 @@ void convert_tmp_rowsets(
}
}
+ // Batch get existing versioned tablet stats if needed
+ std::unordered_map<int64_t, TabletStatsPB> existing_versioned_stats;
+ if (is_versioned_write && !tablet_stats.empty()) {
+ internal_get_load_tablet_stats_batch(code, msg, meta_reader, txn.get(), instance_id,
+ tablet_ids, &existing_versioned_stats);
+ if (code != MetaServiceCode::OK) {
+ LOG(WARNING) << "batch get versioned tablet stats failed, code=" << code
+ << " msg=" << msg << " txn_id=" << txn_id;
+ return;
+ }
+ LOG(INFO) << "batch get " << existing_versioned_stats.size()
+ << " versioned tablet stats, txn_id=" << txn_id;
+ }
+
for (auto& [tablet_id, stats] : tablet_stats) {
DCHECK(tablet_ids.count(tablet_id));
auto& tablet_idx = tablet_ids[tablet_id];
@@ -363,16 +444,7 @@ void convert_tmp_rowsets(
if (code != MetaServiceCode::OK) return;
if (is_versioned_write) {
- TabletStatsPB stats_pb;
- internal_get_versioned_tablet_stats(code, msg, meta_reader, txn.get(), instance_id,
- tablet_idx, stats_pb);
- if (code != MetaServiceCode::OK) {
- LOG(WARNING) << "update versioned tablet stats failed, code=" << code
- << " msg=" << msg << " txn_id=" << txn_id
- << " tablet_id=" << tablet_id;
- return;
- }
-
+ TabletStatsPB stats_pb = existing_versioned_stats[tablet_id];
merge_tablet_stats(stats_pb, stats);
std::string stats_key = versioned::tablet_load_stats_key({instance_id, tablet_id});
@@ -502,12 +574,14 @@ TxnLazyCommitTask::TxnLazyCommitTask(const std::string& instance_id, int64_t txn
}
void TxnLazyCommitTask::commit() {
+ StopWatch sw;
DORIS_CLOUD_DEFER {
{
- std::unique_lock<std::mutex> lock(mutex_);
+ std::unique_lock lock(mutex_);
this->finished_ = true;
}
this->cond_.notify_all();
+ g_bvar_txn_lazy_committer_committing_duration << sw.elapsed_us();
};
int64_t db_id;
@@ -534,7 +608,8 @@ void TxnLazyCommitTask::commit() {
bool is_versioned_write = txn_info.versioned_write();
bool is_versioned_read = txn_info.versioned_read();
- MetaReader meta_reader(instance_id_, txn_kv_.get());
+ CloneChainReader meta_reader(instance_id_, txn_kv_.get(),
+ txn_lazy_committer_->resource_manager().get());
std::stringstream ss;
int retry_times = 0;
@@ -560,213 +635,58 @@ void TxnLazyCommitTask::commit() {
// <partition_id, tmp_rowsets>
std::map<int64_t, std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>>
partition_to_tmp_rowset_metas;
- size_t max_rowset_meta_size = 0;
for (auto& [tmp_rowset_key, tmp_rowset_pb] : all_tmp_rowset_metas) {
partition_to_tmp_rowset_metas[tmp_rowset_pb.partition_id()].emplace_back();
partition_to_tmp_rowset_metas[tmp_rowset_pb.partition_id()].back().first =
tmp_rowset_key;
partition_to_tmp_rowset_metas[tmp_rowset_pb.partition_id()].back().second =
tmp_rowset_pb;
- max_rowset_meta_size = std::max(max_rowset_meta_size, tmp_rowset_pb.ByteSizeLong());
}
- // fdb txn limit 10MB, we use 4MB as the max size for each batch.
- size_t max_rowsets_per_batch = config::txn_lazy_max_rowsets_per_batch;
- if (max_rowset_meta_size > 0) {
- max_rowsets_per_batch = std::min((4UL << 20) / max_rowset_meta_size,
- size_t(config::txn_lazy_max_rowsets_per_batch));
- TEST_SYNC_POINT_CALLBACK("TxnLazyCommitTask::commit::max_rowsets_per_batch",
- &max_rowsets_per_batch, &max_rowset_meta_size);
+ // Shuffle partition ids to reduce the conflict probability
+ std::vector<int64_t> partition_ids;
+ for (const auto& [partition_id, _] : partition_to_tmp_rowset_metas) {
+ partition_ids.push_back(partition_id);
+ }
+ if (config::txn_lazy_commit_shuffle_partitions) {
+ std::mt19937 rng(generate_unique_seed());
+ std::shuffle(partition_ids.begin(), partition_ids.end(), rng);
}
- for (auto& [partition_id, tmp_rowset_metas] : partition_to_tmp_rowset_metas) {
- // tablet_id -> TabletIndexPB
- std::map<int64_t, TabletIndexPB> tablet_ids;
- Versionstamp versionstamp;
- if (is_versioned_write) {
- // Read the versionstamp from the partition key.
- bool is_partition_version_valid = false;
- auto [code, msg] = get_partition_versionstamp(
- txn_kv_.get(), instance_id_, txn_id_, partition_id, &versionstamp,
- &is_partition_version_valid);
+ if (config::enable_cloud_parallel_txn_lazy_commit) {
+ SyncExecutor<std::pair<MetaServiceCode, std::string>> executor(
+ txn_lazy_committer_->parallel_commit_pool(),
+ fmt::format("txn_{}_parallel_commit", txn_id_));
+ for (int64_t partition_id : partition_ids) {
+ executor.add([&, partition_id, this]() {
+ return commit_partition(db_id, partition_id,
+ partition_to_tmp_rowset_metas.at(partition_id),
+ is_versioned_read, is_versioned_write);
+ });
+ }
+ bool finished = false;
+ auto task_results = executor.when_all(&finished);
+ for (auto&& [code, msg] : task_results) {
if (code != MetaServiceCode::OK) {
code_ = code;
- ss << "failed to get partition versionstamp, txn_id=" << txn_id_
- << " partition_id=" << partition_id << " err=" << msg;
- msg_ = ss.str();
- LOG(WARNING) << msg_;
+ msg_ = std::move(msg);
break;
}
- if (!is_partition_version_valid) {
- // The partition version is not valid, it might been committed, skip this partition.
- continue;
- }
- }
-
- for (size_t i = 0; i < tmp_rowset_metas.size(); i += max_rowsets_per_batch) {
- size_t end = (i + max_rowsets_per_batch) > tmp_rowset_metas.size()
- ? tmp_rowset_metas.size()
- : i + max_rowsets_per_batch;
- std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>
- sub_partition_tmp_rowset_metas(tmp_rowset_metas.begin() + i,
- tmp_rowset_metas.begin() + end);
- convert_tmp_rowsets(instance_id_, txn_id_, txn_kv_, code_, msg_, db_id,
- sub_partition_tmp_rowset_metas, tablet_ids,
- is_versioned_write, is_versioned_read, versionstamp);
- if (code_ != MetaServiceCode::OK) break;
}
- if (code_ != MetaServiceCode::OK) break;
-
- std::unique_ptr<Transaction> txn;
- TxnErrorCode err = txn_kv_->create_txn(&txn);
- if (err != TxnErrorCode::TXN_OK) {
- code_ = cast_as<ErrCategory::CREATE>(err);
- ss << "failed to create txn, txn_id=" << txn_id_ << " err=" << err;
- msg_ = ss.str();
- LOG(WARNING) << msg_;
+ if (code_ == MetaServiceCode::OK && !finished) {
+ LOG(WARNING) << "some partition commit tasks not finished, txn_id=" << txn_id_;
+ code_ = MetaServiceCode::KV_TXN_CONFLICT;
break;
}
-
- int64_t table_id = -1;
- DCHECK(tmp_rowset_metas.size() > 0);
- if (table_id <= 0) {
- if (tablet_ids.size() > 0) {
- // get table_id from memory cache
- table_id = tablet_ids.begin()->second.table_id();
- } else if (!is_versioned_read) {
- // get table_id from storage
- int64_t first_tablet_id = tmp_rowset_metas.begin()->second.tablet_id();
- std::string tablet_idx_key =
- meta_tablet_idx_key({instance_id_, first_tablet_id});
- std::string tablet_idx_val;
- err = txn->get(tablet_idx_key, &tablet_idx_val, true);
- if (TxnErrorCode::TXN_OK != err) {
- code_ = err == TxnErrorCode::TXN_KEY_NOT_FOUND
- ? MetaServiceCode::TXN_ID_NOT_FOUND
- : cast_as<ErrCategory::READ>(err);
- ss << "failed to get tablet idx, txn_id=" << txn_id_
- << " key=" << hex(tablet_idx_key) << " err=" << err;
- msg_ = ss.str();
- LOG(WARNING) << msg_;
- break;
- }
-
- TabletIndexPB tablet_idx_pb;
- if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
- code_ = MetaServiceCode::PROTOBUF_PARSE_ERR;
- ss << "failed to parse tablet idx pb txn_id=" << txn_id_
- << " key=" << hex(tablet_idx_key);
- msg_ = ss.str();
- break;
- }
- table_id = tablet_idx_pb.table_id();
- } else {
- TabletIndexPB tablet_idx_pb;
- int64_t first_tablet_id = tmp_rowset_metas.begin()->second.tablet_id();
- err = meta_reader.get_tablet_index(txn.get(), first_tablet_id,
- &tablet_idx_pb);
- if (err != TxnErrorCode::TXN_OK) {
- code_ = err == TxnErrorCode::TXN_KEY_NOT_FOUND
- ? MetaServiceCode::TXN_ID_NOT_FOUND
- : cast_as<ErrCategory::READ>(err);
- ss << "failed to get tablet index, txn_id=" << txn_id_
- << " tablet_id=" << first_tablet_id << " err=" << err;
- msg_ = ss.str();
- LOG(WARNING) << msg_;
- break;
- }
- table_id = tablet_idx_pb.table_id();
- }
- }
-
- DCHECK(table_id > 0);
- DCHECK(partition_id > 0);
-
- VersionPB version_pb;
- std::string ver_val;
- std::string ver_key =
- partition_version_key({instance_id_, db_id, table_id, partition_id});
- if (!is_versioned_read) {
- err = txn->get(ver_key, &ver_val);
- if (TxnErrorCode::TXN_OK != err) {
- code_ = err == TxnErrorCode::TXN_KEY_NOT_FOUND
- ? MetaServiceCode::TXN_ID_NOT_FOUND
- : cast_as<ErrCategory::READ>(err);
- ss << "failed to get partiton version, txn_id=" << txn_id_
- << " key=" << hex(ver_key) << " err=" << err;
- msg_ = ss.str();
- LOG(WARNING) << msg_;
- break;
- }
- if (!version_pb.ParseFromString(ver_val)) {
- code_ = MetaServiceCode::PROTOBUF_PARSE_ERR;
- ss << "failed to parse version pb txn_id=" << txn_id_
- << " key=" << hex(ver_key);
- msg_ = ss.str();
- break;
- }
- } else {
- err = meta_reader.get_partition_version(txn.get(), partition_id, &version_pb,
- nullptr);
- if (TxnErrorCode::TXN_OK != err) {
- code_ = err == TxnErrorCode::TXN_KEY_NOT_FOUND
- ? MetaServiceCode::TXN_ID_NOT_FOUND
- : cast_as<ErrCategory::READ>(err);
- ss << "failed to get versioned partiton version, txn_id=" << txn_id_
- << " partition_id=" << partition_id << " err=" << err;
- msg_ = ss.str();
- LOG(WARNING) << msg_;
- break;
- }
- }
-
- if (version_pb.pending_txn_ids_size() > 0 &&
- version_pb.pending_txn_ids(0) == txn_id_) {
- DCHECK(version_pb.pending_txn_ids_size() == 1);
- version_pb.clear_pending_txn_ids();
- ver_val.clear();
-
- if (version_pb.has_version()) {
- version_pb.set_version(version_pb.version() + 1);
- } else {
- // first commit txn version is 2
- version_pb.set_version(2);
- }
- if (!version_pb.SerializeToString(&ver_val)) {
- code_ = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
- ss << "failed to serialize version_pb when saving, txn_id=" << txn_id_;
- msg_ = ss.str();
- break;
- }
- txn->put(ver_key, ver_val);
- LOG(INFO) << "put ver_key=" << hex(ver_key) << " txn_id=" << txn_id_
- << " version_pb=" << version_pb.ShortDebugString();
- if (is_versioned_write) {
- // Update the partition version with the specified versionstamp.
- std::string versioned_key =
- versioned::partition_version_key({instance_id_, partition_id});
- versioned_put(txn.get(), versioned_key, versionstamp, ver_val);
- LOG(INFO) << "put versioned ver_key=" << hex(versioned_key)
- << " txn_id=" << txn_id_
- << " version_pb=" << version_pb.ShortDebugString();
- }
-
- for (auto& [tmp_rowset_key, tmp_rowset_pb] : tmp_rowset_metas) {
- txn->remove(tmp_rowset_key);
- LOG(INFO) << "remove tmp_rowset_key=" << hex(tmp_rowset_key)
- << " txn_id=" << txn_id_;
- }
-
- TEST_SYNC_POINT_CALLBACK("TxnLazyCommitter::commit");
- err = txn->commit();
- if (err != TxnErrorCode::TXN_OK) {
- code_ = cast_as<ErrCategory::COMMIT>(err);
- ss << "failed to commit kv txn, txn_id=" << txn_id_ << " err=" << err;
- msg_ = ss.str();
- break;
- }
+ } else {
+ for (int64_t partition_id : partition_ids) {
+ std::tie(code_, msg_) = commit_partition(
+ db_id, partition_id, partition_to_tmp_rowset_metas[partition_id],
+ is_versioned_read, is_versioned_write);
+ if (code_ != MetaServiceCode::OK) break;
}
}
+
if (code_ != MetaServiceCode::OK) {
LOG(WARNING) << "txn_id=" << txn_id_ << " code=" << code_ << " msg=" << msg_;
break;
@@ -777,34 +697,199 @@ void TxnLazyCommitTask::commit() {
retry_times++ < config::txn_store_retry_times);
}
+std::pair<MetaServiceCode, std::string> TxnLazyCommitTask::commit_partition(
+ int64_t db_id, int64_t partition_id,
+ const std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>& tmp_rowset_metas,
+ bool is_versioned_read, bool is_versioned_write) {
+ std::stringstream ss;
+ CloneChainReader meta_reader(instance_id_, txn_kv_.get(),
+ txn_lazy_committer_->resource_manager().get());
+ MetaServiceCode code;
+ std::string msg;
+
+ StopWatch sw;
+ DORIS_CLOUD_DEFER {
+ g_bvar_txn_lazy_committer_commit_partition_duration << sw.elapsed_us();
+ };
+
+ // tablet_id -> TabletIndexPB
+ std::map<int64_t, TabletIndexPB> tablet_ids;
+ int64_t table_id = -1;
+ {
+ DCHECK(tmp_rowset_metas.size() > 0);
+ int64_t first_tablet_id = tmp_rowset_metas.begin()->second.tablet_id();
+ TabletIndexPB first_tablet_index;
+ std::tie(code, msg) =
+ get_tablet_index(meta_reader, txn_kv_.get(), instance_id_, txn_id_, first_tablet_id,
+ &first_tablet_index, is_versioned_read);
+ if (code != MetaServiceCode::OK) {
+ return {code, msg};
+ }
+ table_id = first_tablet_index.table_id();
+ tablet_ids.emplace(first_tablet_id, first_tablet_index);
+ }
+
+ // The partition version key is constructed during the txn commit process, so the versionstamp
+ // can be retrieved from the key itself.
+ Versionstamp versionstamp;
+ VersionPB original_partition_version;
+ std::tie(code, msg) = get_partition_version(txn_kv_.get(), instance_id_, txn_id_, db_id,
+ table_id, partition_id, &original_partition_version,
+ &versionstamp, is_versioned_read);
+ if (code != MetaServiceCode::OK) {
+ return {code, msg};
+ } else if (original_partition_version.pending_txn_ids_size() == 0 ||
+ original_partition_version.pending_txn_ids(0) != txn_id_) {
+ // The partition version does not contain the target pending txn, it might have been committed
+ LOG(INFO) << "txn_id=" << txn_id_ << " partition_id=" << partition_id
+ << " version has already been converted."
+ << " version_pb:" << original_partition_version.ShortDebugString();
+ TEST_SYNC_POINT_CALLBACK("TxnLazyCommitTask::commit::already_been_converted",
+ &original_partition_version);
+ return {MetaServiceCode::OK, ""};
+ }
+
+ size_t max_rowset_meta_size = 0;
+ for (const auto& [_, tmp_rowset_pb] : tmp_rowset_metas) {
+ max_rowset_meta_size = std::max(max_rowset_meta_size, tmp_rowset_pb.ByteSizeLong());
+ }
+
+ // fdb txn limit 10MB, we use 4MB as the max size for each batch.
+ size_t max_rowsets_per_batch = config::txn_lazy_max_rowsets_per_batch;
+ if (max_rowset_meta_size > 0) {
+ max_rowsets_per_batch = std::min((4UL << 20) / max_rowset_meta_size,
+ size_t(config::txn_lazy_max_rowsets_per_batch));
+ TEST_SYNC_POINT_CALLBACK("TxnLazyCommitTask::commit::max_rowsets_per_batch",
+ &max_rowsets_per_batch, &max_rowset_meta_size);
+ }
+
+ for (size_t i = 0; i < tmp_rowset_metas.size(); i += max_rowsets_per_batch) {
+ size_t end = (i + max_rowsets_per_batch) > tmp_rowset_metas.size()
+ ? tmp_rowset_metas.size()
+ : i + max_rowsets_per_batch;
+ std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>
+ sub_partition_tmp_rowset_metas(tmp_rowset_metas.begin() + i,
+ tmp_rowset_metas.begin() + end);
+ convert_tmp_rowsets(instance_id_, txn_id_, txn_kv_, code, msg, db_id,
+ sub_partition_tmp_rowset_metas, tablet_ids, is_versioned_write,
+ is_versioned_read, versionstamp,
+ txn_lazy_committer_->resource_manager().get());
+ if (code != MetaServiceCode::OK) {
+ return {code, msg};
+ }
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ code = cast_as<ErrCategory::CREATE>(err);
+ ss << "failed to create txn, txn_id=" << txn_id_ << " err=" << err;
+ msg = ss.str();
+ LOG(WARNING) << msg;
+ return {code, msg};
+ }
+
+ DCHECK(table_id > 0);
+ DCHECK(partition_id > 0);
+
+ // Notice: get the versionstamp again, since it must not be changed here.
+ // But if you want to support multi pending txns in the partition version, this must be changed.
+ VersionPB version_pb;
+ std::tie(code, msg) =
+ get_partition_version(txn.get(), instance_id_, txn_id_, db_id, table_id, partition_id,
+ &version_pb, &versionstamp, is_versioned_read);
+ if (code != MetaServiceCode::OK) {
+ return {code, msg};
+ }
+
+ if (version_pb.pending_txn_ids_size() > 0 && version_pb.pending_txn_ids(0) == txn_id_) {
+ DCHECK(version_pb.pending_txn_ids_size() == 1);
+ version_pb.clear_pending_txn_ids();
+
+ if (version_pb.has_version()) {
+ version_pb.set_version(version_pb.version() + 1);
+ } else {
+ // first commit txn version is 2
+ version_pb.set_version(2);
+ }
+ std::string ver_key = partition_version_key({instance_id_, db_id, table_id, partition_id});
+ std::string ver_val;
+ if (!version_pb.SerializeToString(&ver_val)) {
+ code = MetaServiceCode::PROTOBUF_SERIALIZE_ERR;
+ ss << "failed to serialize version_pb when saving, txn_id=" << txn_id_;
+ msg = ss.str();
+ return {code, msg};
+ }
+ txn->put(ver_key, ver_val);
+ LOG(INFO) << "put ver_key=" << hex(ver_key) << " txn_id=" << txn_id_
+ << " version_pb=" << version_pb.ShortDebugString();
+ if (is_versioned_write) {
+ // Update the partition version with the specified versionstamp.
+ std::string versioned_key =
+ versioned::partition_version_key({instance_id_, partition_id});
+ versioned_put(txn.get(), versioned_key, versionstamp, ver_val);
+ LOG(INFO) << "put versioned ver_key=" << hex(versioned_key) << " txn_id=" << txn_id_
+ << " version_pb=" << version_pb.ShortDebugString();
+ }
+
+ for (auto& [tmp_rowset_key, tmp_rowset_pb] : tmp_rowset_metas) {
+ txn->remove(tmp_rowset_key);
+ LOG(INFO) << "remove tmp_rowset_key=" << hex(tmp_rowset_key) << " txn_id=" << txn_id_;
+ }
+
+ TEST_SYNC_POINT_CALLBACK("TxnLazyCommitter::commit");
+ err = txn->commit();
+ if (err != TxnErrorCode::TXN_OK) {
+ code = cast_as<ErrCategory::COMMIT>(err);
+ ss << "failed to commit kv txn, txn_id=" << txn_id_ << " err=" << err;
+ msg = ss.str();
+ return {code, msg};
+ }
+ }
+ return {MetaServiceCode::OK, ""};
+}
+
std::pair<MetaServiceCode, std::string> TxnLazyCommitTask::wait() {
+ constexpr auto WAIT_FOR_MICROSECONDS = 5 * 1000000;
+
StopWatch sw;
uint64_t round = 0;
- while (true) {
- std::unique_lock<std::mutex> lock(mutex_);
- if (cond_.wait_for(lock, std::chrono::seconds(5),
- [this]() { return this->finished_ == true; })) {
- break;
+ {
+ std::unique_lock lock(mutex_);
+ while (!finished_) {
+ if (cond_.wait_for(lock, WAIT_FOR_MICROSECONDS) == ETIMEDOUT) {
+ LOG(INFO) << "txn_id=" << txn_id_ << " wait_for 5s timeout round=" << ++round;
+ }
}
- LOG(INFO) << "txn_id=" << txn_id_ << " wait_for 5s timeout round=" << ++round;
}
- txn_lazy_committer_->remove(txn_id_);
-
sw.pause();
+ g_bvar_txn_lazy_committer_waiting_duration << sw.elapsed_us();
if (sw.elapsed_us() > 1000000) {
LOG(INFO) << "txn_lazy_commit task wait more than 1000ms, cost=" << sw.elapsed_us() / 1000
- << " ms"
- << " txn_id=" << txn_id_;
+ << " ms txn_id=" << txn_id_;
}
return std::make_pair(this->code_, this->msg_);
}
-TxnLazyCommitter::TxnLazyCommitter(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(txn_kv) {
+TxnLazyCommitter::TxnLazyCommitter(std::shared_ptr<TxnKv> txn_kv)
+ : TxnLazyCommitter(txn_kv, std::make_shared<ResourceManager>(txn_kv)) {}
+
+TxnLazyCommitter::TxnLazyCommitter(std::shared_ptr<TxnKv> txn_kv,
+ std::shared_ptr<ResourceManager> resource_mgr)
+ : txn_kv_(txn_kv), resource_mgr_(std::move(resource_mgr)) {
worker_pool_ = std::make_unique<SimpleThreadPool>(config::txn_lazy_commit_num_threads,
"txn_lazy_commiter");
worker_pool_->start();
+
+ int32_t parallel_commit_threads = std::max(0, config::parallel_txn_lazy_commit_num_threads);
+ if (parallel_commit_threads == 0) {
+ parallel_commit_threads = std::thread::hardware_concurrency();
+ }
+ parallel_commit_pool_ =
+ std::make_shared<SimpleThreadPool>(parallel_commit_threads, "parallel_commit");
+ parallel_commit_pool_->start();
}
/**
@@ -827,9 +912,14 @@ std::shared_ptr<TxnLazyCommitTask> TxnLazyCommitter::submit(const std::string& i
task = std::make_shared<TxnLazyCommitTask>(instance_id, txn_id, txn_kv_, this);
running_tasks_.emplace(txn_id, task);
+ g_bvar_txn_lazy_committer_submitted << 1;
}
- worker_pool_->submit([task]() { task->commit(); });
+ worker_pool_->submit([task]() {
+ task->commit();
+ task->txn_lazy_committer_->remove(task->txn_id_);
+ g_bvar_txn_lazy_committer_finished << 1;
+ });
DCHECK(task != nullptr);
return task;
}
diff --git a/cloud/src/meta-service/txn_lazy_committer.h b/cloud/src/meta-service/txn_lazy_committer.h
index 1bcfa317a5d..8ab62aff89f 100644
--- a/cloud/src/meta-service/txn_lazy_committer.h
+++ b/cloud/src/meta-service/txn_lazy_committer.h
@@ -17,12 +17,16 @@
#pragma once
+#include <bthread/condition_variable.h>
+#include <bthread/mutex.h>
#include <gen_cpp/cloud.pb.h>
-#include <atomic>
+#include <memory>
#include "common/simple_thread_pool.h"
+#include "meta-store/clone_chain_reader.h"
#include "meta-store/txn_kv.h"
+#include "resource-manager/resource_manager.h"
namespace doris::cloud {
@@ -36,14 +40,21 @@ public:
std::pair<MetaServiceCode, std::string> wait();
+ int64_t txn_id() const { return txn_id_; }
+
private:
friend class TxnLazyCommitter;
+ std::pair<MetaServiceCode, std::string> commit_partition(
+ int64_t db_id, int64_t partition_id,
+ const std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>& tmp_rowset_metas,
+ bool is_versioned_write, bool is_versioned_read);
+
std::string instance_id_;
int64_t txn_id_;
std::shared_ptr<TxnKv> txn_kv_;
- std::mutex mutex_;
- std::condition_variable cond_;
+ bthread::Mutex mutex_;
+ bthread::ConditionVariable cond_;
bool finished_ = false;
MetaServiceCode code_ = MetaServiceCode::OK;
std::string msg_;
@@ -53,13 +64,19 @@ private:
class TxnLazyCommitter {
public:
TxnLazyCommitter(std::shared_ptr<TxnKv> txn_kv);
+ TxnLazyCommitter(std::shared_ptr<TxnKv> txn_kv, std::shared_ptr<ResourceManager> resource_mgr);
std::shared_ptr<TxnLazyCommitTask> submit(const std::string& instance_id, int64_t txn_id);
void remove(int64_t txn_id);
+ std::shared_ptr<ResourceManager>& resource_manager() { return resource_mgr_; }
+ std::shared_ptr<SimpleThreadPool>& parallel_commit_pool() { return parallel_commit_pool_; }
+
private:
std::shared_ptr<TxnKv> txn_kv_;
+ std::shared_ptr<ResourceManager> resource_mgr_;
std::unique_ptr<SimpleThreadPool> worker_pool_;
+ std::shared_ptr<SimpleThreadPool> parallel_commit_pool_;
std::mutex mutex_;
// <txn_id, TxnLazyCommitTask>
diff --git a/cloud/src/meta-store/CMakeLists.txt b/cloud/src/meta-store/CMakeLists.txt
index 7e2a60916e6..fba732c1110 100644
--- a/cloud/src/meta-store/CMakeLists.txt
+++ b/cloud/src/meta-store/CMakeLists.txt
@@ -6,6 +6,7 @@ set(EXECUTABLE_OUTPUT_PATH "${BUILD_DIR}/src/meta-store")
add_library(MetaStore STATIC
blob_message.cpp
+ clone_chain_reader.cpp
codec.cpp
document_message.cpp
keys.cpp
diff --git a/cloud/src/meta-store/blob_message.cpp b/cloud/src/meta-store/blob_message.cpp
index 0ada3eca56d..90b2f298884 100644
--- a/cloud/src/meta-store/blob_message.cpp
+++ b/cloud/src/meta-store/blob_message.cpp
@@ -21,6 +21,8 @@
#include <butil/iobuf_inl.h>
#include <google/protobuf/message.h>
+#include <cstdint>
+
#include "common/logging.h"
#include "common/util.h"
#include "meta-store/codec.h"
@@ -159,4 +161,180 @@ void blob_put(Transaction* txn, std::string_view key, std::string_view value, ui
}
}
+BlobIterator::BlobIterator(std::unique_ptr<FullRangeGetIterator> iter)
+ : error_code_(TxnErrorCode::TXN_OK), iter_(std::move(iter)) {
+ // Load the first blob
+ next();
+}
+
+bool BlobIterator::valid() const {
+ return error_code_ == TxnErrorCode::TXN_OK && is_underlying_iter_valid() &&
+ // ... or it has reached the end of blobs
+ current_blob_key_.size() > 0;
+}
+
+TxnErrorCode BlobIterator::error_code() const {
+ if (error_code_ != TxnErrorCode::TXN_OK) {
+ return error_code_;
+ }
+ if (!iter_) {
+ return TxnErrorCode::TXN_INVALID_DATA;
+ }
+ return iter_->error_code();
+}
+
+void BlobIterator::next() {
+ // Switch to next blob, so clear previous state
+ version_ = -1;
+ current_blob_key_.clear();
+ current_blob_values_.clear();
+ current_blob_raw_keys_.clear();
+
+ if (error_code_ == TxnErrorCode::TXN_OK && is_underlying_iter_valid() && iter_->has_next()) {
+ load_current_blob();
+ }
+}
+
+bool BlobIterator::parse_value(google::protobuf::Message* pb) const {
+ butil::IOBuf merge;
+ for (auto&& value : current_blob_values_) {
+ merge.append_user_data((void*)value.data(), value.size(), +[](void*) {});
+ }
+ butil::IOBufAsZeroCopyInputStream merge_stream(merge);
+ return pb->ParseFromZeroCopyStream(&merge_stream);
+}
+
+void BlobIterator::load_current_blob() {
+ uint16_t next_sequence = 0;
+ if (auto&& kvp = iter_->peek(); !kvp.has_value()) {
+ // All keys have been processed.
+ return;
+ } else if (!extract_origin_key(kvp->first, ¤t_blob_key_, &version_, &next_sequence)) {
+ return;
+ }
+
+ while (iter_->is_valid() && iter_->has_next()) {
+ auto [k, v] = *(iter_->peek());
+
+ // Is this key part of the current blob?
+ std::string origin_key;
+ uint8_t version = -1;
+ uint16_t sequence = -1;
+ if (!extract_origin_key(k, &origin_key, &version, &sequence) ||
+ origin_key != current_blob_key_) {
+ return;
+ } else if (version != version_ || sequence != next_sequence) {
+ LOG_WARNING("blob key version or sequence mismatch")
+ .tag("expected_version", version_)
+ .tag("actual_version", version)
+ .tag("expected_sequence", next_sequence)
+ .tag("actual_sequence", sequence)
+ .tag("key", hex(k));
+ error_code_ = TxnErrorCode::TXN_INVALID_DATA;
+ return;
+ }
+
+ current_blob_raw_keys_.push_back(std::string(k));
+ current_blob_values_.push_back(std::string(v));
+ iter_->next();
+ next_sequence++;
+ }
+}
+
+bool BlobIterator::extract_origin_key(std::string_view raw_key, std::string* output,
+ uint8_t* version, uint16_t* sequence) {
+ // The suffix is 8 bytes: |version(1)|dummy(5)|sequence(2)|
+ if (raw_key.size() < 9) {
+ LOG_WARNING("failed to extract origin key").tag("key", hex(raw_key));
+ error_code_ = TxnErrorCode::TXN_INVALID_DATA;
+ return false;
+ }
+
+ const size_t origin_key_size = raw_key.size() - 9;
+ std::string_view origin_key = raw_key.substr(0, origin_key_size);
+ raw_key.remove_prefix(origin_key_size);
+ int64_t suffix = 0;
+ if (decode_int64(&raw_key, &suffix) != 0) {
+ LOG_WARNING("failed to decode int64")
+ .tag("key", hex(raw_key))
+ .tag("origin_key", hex(origin_key));
+ error_code_ = TxnErrorCode::TXN_INVALID_DATA;
+ return false;
+ }
+
+ *version = (suffix >> 56) & 0xff;
+ *sequence = suffix & 0xffff;
+ *output = std::string(origin_key);
+
+ return true;
+}
+
+std::unique_ptr<BlobIterator> blob_get_range(const std::shared_ptr<TxnKv>& txn_kv,
+ std::string_view begin_key, std::string_view end_key,
+ bool snapshot) {
+ FullRangeGetOptions options;
+ options.txn_kv = txn_kv;
+ options.prefetch = true;
+ options.snapshot = snapshot;
+ std::unique_ptr<FullRangeGetIterator> iter =
+ txn_kv->full_range_get(std::string(begin_key), std::string(end_key), options);
+
+ return std::make_unique<BlobIterator>(std::move(iter));
+}
+
+std::unique_ptr<BlobIterator> blob_get_range(Transaction* txn, std::string_view begin_key,
+ std::string_view end_key, bool snapshot) {
+ FullRangeGetOptions options;
+ options.prefetch = true;
+ options.snapshot = snapshot;
+ std::unique_ptr<FullRangeGetIterator> iter =
+ txn->full_range_get(std::string(begin_key), std::string(end_key), options);
+
+ return std::make_unique<BlobIterator>(std::move(iter));
+}
+
+namespace versioned {
+
+void blob_put(Transaction* txn, std::string_view key, std::string_view value, uint8_t ver,
+ size_t split_size) {
+ std::string encoded_key(key);
+ uint32_t offset = encode_versionstamp(Versionstamp::min(), &encoded_key);
+ encode_versionstamp_end(&encoded_key);
+
+ auto split_vec = split_string(value, split_size);
+ int64_t suffix_base = ver;
+ suffix_base <<= 56;
+ for (size_t i = 0; i < split_vec.size(); ++i) {
+ std::string k(encoded_key);
+ encode_int64(suffix_base + i, &k);
+ txn->atomic_set_ver_key(k, offset, split_vec[i]);
+ }
+}
+
+void blob_put(Transaction* txn, std::string_view key, const google::protobuf::Message& pb,
+ uint8_t ver, size_t split_size) {
+ std::string value;
+ bool ret = pb.SerializeToString(&value); // Always success
+ DCHECK(ret) << hex(key) << ' ' << pb.ShortDebugString();
+ versioned::blob_put(txn, key, value, ver, split_size);
+}
+
+void blob_put(Transaction* txn, std::string_view key, Versionstamp vs, std::string_view value,
+ uint8_t ver, size_t split_size) {
+ std::string encoded_key(key);
+ encode_versionstamp(vs, &encoded_key);
+ encode_versionstamp_end(&encoded_key);
+ // Avoid set versionstamp again
+ doris::cloud::blob_put(txn, encoded_key, value, ver, split_size);
+}
+
+void blob_put(Transaction* txn, std::string_view key, Versionstamp vs,
+ const google::protobuf::Message& pb, uint8_t ver, size_t split_size) {
+ std::string value;
+ bool ret = pb.SerializeToString(&value); // Always success
+ DCHECK(ret) << hex(key) << ' ' << pb.ShortDebugString();
+ versioned::blob_put(txn, key, vs, value, ver, split_size);
+}
+
+} // namespace versioned
} // namespace doris::cloud
diff --git a/cloud/src/meta-store/blob_message.h b/cloud/src/meta-store/blob_message.h
index 4bba034bf0e..25d5ad30366 100644
--- a/cloud/src/meta-store/blob_message.h
+++ b/cloud/src/meta-store/blob_message.h
@@ -17,6 +17,7 @@
#pragma once
+#include <string>
#include <string_view>
#include "meta-store/txn_kv.h"
@@ -94,4 +95,114 @@ void blob_put(Transaction* txn, std::string_view key, const google::protobuf::Me
void blob_put(Transaction* txn, std::string_view key, std::string_view value, uint8_t ver,
size_t split_size = 90 * 1000);
+// Iterator for blob key-value pairs.
+//
+// The keys with the same origin key are considered as a blob. The origin key is obtained by
+// removing the sequence suffix from the raw key.
+//
+// ATTN: This iterator is not compatible with the old style blob keys (without sequence suffix).
+//
+// Usage:
+// auto iter = blob_get_range(txn_kv, begin_key, end_key);
+// for (; iter->valid(); iter->next()) {
+// // Process the current blob
+// auto origin_key = iter->key();
+// auto version = iter->version();
+// auto raw_keys = iter->raw_keys();
+// auto values = iter->values();
+// // Or parse the blob value into a protobuf message
+// YourProtoMessage pb;
+// if (iter->parse_value(&pb)) {
+// // Successfully parsed
+// }
+// }
+// if (iter->error_code() != TxnErrorCode::TXN_OK) {
+// // Handle error
+// }
+class BlobIterator {
+public:
+ BlobIterator(std::unique_ptr<FullRangeGetIterator> iter);
+ ~BlobIterator() = default;
+
+ BlobIterator(const BlobIterator&) = delete;
+ BlobIterator& operator=(const BlobIterator&) = delete;
+
+ // There are two states of validity:
+ // 1. The iterator is valid and points to a blob (a set of KVs with the same origin key).
+ // In this state, `valid()` returns true.
+ // 2. The iterator is invalid (either due to an error or because it has reached the end).
+ // In this state, `valid()` returns false.
+ bool valid() const;
+
+ // Move to the next blob.
+ //
+ // If there is no next blob, the iterator becomes invalid.
+ void next();
+
+ // Get the error code of the iterator. If the iterator has reached the end, returns TXN_OK.
+ TxnErrorCode error_code() const;
+
+ // Return the version of the current blob. `valid()` must be true before calling this method.
+ uint8_t version() const { return version_; }
+
+ // Return the origin key of the current blob. `valid()` must be true before calling this method.
+ std::string_view key() const { return current_blob_key_; }
+
+ // Return the raw keys of the current blob. `valid()` must be true before calling this method.
+ const std::vector<std::string>& raw_keys() const { return current_blob_raw_keys_; }
+
+ // Return the values of the current blob. `valid()` must be true before calling this method.
+ const std::vector<std::string>& values() const { return current_blob_values_; }
+
+ // Parse the value of the current blob into the given protobuf message. `valid()` must be true before calling this method.
+ bool parse_value(google::protobuf::Message* pb) const;
+
+private:
+ bool is_underlying_iter_valid() const { return iter_ && iter_->is_valid(); }
+
+ void load_current_blob();
+ bool extract_origin_key(std::string_view raw_key, std::string* origin_key, uint8_t* version,
+ uint16_t* sequence);
+
+ TxnErrorCode error_code_ = TxnErrorCode::TXN_OK;
+ std::unique_ptr<FullRangeGetIterator> iter_;
+ uint8_t version_ = 0;
+ std::string current_blob_key_;
+ std::vector<std::string> current_blob_raw_keys_;
+ std::vector<std::string> current_blob_values_;
+};
+
+// Get a range of blob key-value pairs.
+//
+// It requires that all keys in the range are in the new blob format (with sequence suffix).
+std::unique_ptr<BlobIterator> blob_get_range(const std::shared_ptr<TxnKv>& txn_kv,
+ std::string_view begin_key, std::string_view end_key,
+ bool snapshot = false);
+
+// Get a range of blob key-value pairs.
+//
+// It requires that all keys in the range are in the new blob format (with sequence suffix).
+std::unique_ptr<BlobIterator> blob_get_range(Transaction* txn, std::string_view begin_key,
+ std::string_view end_key, bool snapshot = false);
+
+namespace versioned {
+
+// Put a blob message with a auto generated versionstamp.
+void blob_put(Transaction* txn, std::string_view key, const google::protobuf::Message& pb,
+ uint8_t ver = 0, size_t split_size = 90 * 1000);
+
+// Put a blob message with a auto generated versionstamp.
+void blob_put(Transaction* txn, std::string_view key, std::string_view value, uint8_t ver = 0,
+ size_t split_size = 90 * 1000);
+
+// Put a blob message with a specified versionstamp.
+void blob_put(Transaction* txn, std::string_view key, Versionstamp v,
+ const google::protobuf::Message& pb, uint8_t ver = 0, size_t split_size = 90 * 1000);
+
+// Put a blob message with a specified versionstamp.
+void blob_put(Transaction* txn, std::string_view key, Versionstamp v, std::string_view value,
+ uint8_t ver = 0, size_t split_size = 90 * 1000);
+
+} // namespace versioned
+
} // namespace doris::cloud
diff --git a/cloud/src/meta-store/clone_chain_reader.cpp b/cloud/src/meta-store/clone_chain_reader.cpp
new file mode 100644
index 00000000000..06ed82847b0
--- /dev/null
+++ b/cloud/src/meta-store/clone_chain_reader.cpp
@@ -0,0 +1,1338 @@
+// 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 "clone_chain_reader.h"
+
+#include "common/logging.h"
+#include "common/util.h"
+#include "meta-store/blob_message.h"
+#include "meta-store/keys.h"
+#include "meta-store/meta_reader.h"
+#include "meta-store/txn_kv_error.h"
+#include "meta-store/versionstamp.h"
+#include "resource-manager/resource_manager.h"
+
+namespace doris::cloud {
+
+bool CloneChainReader::get_source_snapshot_info(const std::string& instance_id,
+ std::string* source_instance_id,
+ Versionstamp* source_snapshot_version) {
+ return resource_mgr_->get_source_snapshot_info(instance_id, source_instance_id,
+ source_snapshot_version);
+}
+
+TxnErrorCode CloneChainReader::get_table_version(int64_t table_id, Versionstamp* table_version,
+ bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_table_version(txn.get(), table_id, table_version, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_table_version(Transaction* txn, int64_t table_id,
+ Versionstamp* table_version, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err = reader.get_table_version(txn, table_id, table_version, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ if (err == TxnErrorCode::TXN_OK) {
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+ }
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_table_versions(
+ const std::vector<int64_t>& table_ids,
+ std::unordered_map<int64_t, Versionstamp>* table_versions, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_table_versions(txn.get(), table_ids, table_versions, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_table_versions(
+ Transaction* txn, const std::vector<int64_t>& table_ids,
+ std::unordered_map<int64_t, Versionstamp>* table_versions, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ std::vector<int64_t> remaining_ids = table_ids;
+
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ std::unordered_map<int64_t, Versionstamp> current_versions;
+ TxnErrorCode err =
+ reader.get_table_versions(txn, remaining_ids, ¤t_versions, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ min_read_versionstamp_ = std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+
+ // Add found results to output
+ for (const auto& [table_id, version] : current_versions) {
+ (*table_versions)[table_id] = version;
+ }
+
+ // Remove found ids from remaining_ids
+ std::vector<int64_t> new_remaining_ids;
+ for (int64_t table_id : remaining_ids) {
+ if (!current_versions.contains(table_id)) {
+ new_remaining_ids.push_back(table_id);
+ }
+ }
+ remaining_ids = std::move(new_remaining_ids);
+
+ // If all found or no more to search, break
+ if (remaining_ids.empty()) {
+ break;
+ }
+
+ // Try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain, remaining ids are not found
+ break;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+
+ return TxnErrorCode::TXN_OK;
+}
+
+TxnErrorCode CloneChainReader::get_partition_version(int64_t partition_id, VersionPB* version,
+ Versionstamp* versionstamp, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_partition_version(txn.get(), partition_id, version, versionstamp, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_partition_version(Transaction* txn, int64_t partition_id,
+ VersionPB* version, Versionstamp* versionstamp,
+ bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err =
+ reader.get_partition_version(txn, partition_id, version, versionstamp, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ if (err == TxnErrorCode::TXN_OK) {
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+ }
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_partition_versions(
+ const std::vector<int64_t>& partition_ids, std::unordered_map<int64_t, VersionPB>* versions,
+ std::unordered_map<int64_t, Versionstamp>* versionstamps, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_partition_versions(txn.get(), partition_ids, versions, versionstamps, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_partition_versions(
+ Transaction* txn, const std::vector<int64_t>& partition_ids,
+ std::unordered_map<int64_t, VersionPB>* versions,
+ std::unordered_map<int64_t, Versionstamp>* versionstamps, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ std::vector<int64_t> remaining_ids = partition_ids;
+
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ std::unordered_map<int64_t, VersionPB> current_versions;
+ std::unordered_map<int64_t, Versionstamp> current_versionstamps;
+ TxnErrorCode err = reader.get_partition_versions(txn, remaining_ids, ¤t_versions,
+ ¤t_versionstamps, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ min_read_versionstamp_ = std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+
+ // Add found results to output
+ if (versions) {
+ for (const auto& [partition_id, version] : current_versions) {
+ (*versions)[partition_id] = std::move(version);
+ }
+ }
+ if (versionstamps) {
+ for (const auto& [partition_id, versionstamp] : current_versionstamps) {
+ (*versionstamps)[partition_id] = versionstamp;
+ }
+ }
+
+ // Remove found ids from remaining_ids
+ std::vector<int64_t> new_remaining_ids;
+ for (int64_t partition_id : remaining_ids) {
+ if (!current_versions.contains(partition_id)) {
+ new_remaining_ids.push_back(partition_id);
+ }
+ }
+ remaining_ids = std::move(new_remaining_ids);
+
+ // If all found or no more to search, break
+ if (remaining_ids.empty()) {
+ break;
+ }
+
+ // Try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain, remaining ids are not found
+ break;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+
+ return TxnErrorCode::TXN_OK;
+}
+
+TxnErrorCode CloneChainReader::get_partition_versions(
+ Transaction* txn, const std::vector<int64_t>& partition_ids,
+ std::unordered_map<int64_t, int64_t>* versions, int64_t* last_pending_txn_id,
+ bool snapshot) {
+ std::unordered_map<int64_t, VersionPB> version_pb_map;
+ TxnErrorCode err =
+ get_partition_versions(txn, partition_ids, &version_pb_map, nullptr, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+
+ for (int64_t partition_id : partition_ids) {
+ auto it = version_pb_map.find(partition_id);
+ if (it == version_pb_map.end()) {
+ versions->emplace(partition_id, 1);
+ } else {
+ const VersionPB& version_pb = it->second;
+ int64_t version = version_pb.version();
+ versions->emplace(partition_id, version);
+ if (last_pending_txn_id && version_pb.pending_txn_ids_size() > 0) {
+ *last_pending_txn_id = version_pb.pending_txn_ids(0);
+ }
+ }
+ }
+
+ return TxnErrorCode::TXN_OK;
+}
+
+TxnErrorCode CloneChainReader::get_tablet_load_stats(int64_t tablet_id, TabletStatsPB* tablet_stats,
+ Versionstamp* versionstamp, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_tablet_load_stats(txn.get(), tablet_id, tablet_stats, versionstamp, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_load_stats(Transaction* txn, int64_t tablet_id,
+ TabletStatsPB* tablet_stats,
+ Versionstamp* versionstamp, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err =
+ reader.get_tablet_load_stats(txn, tablet_id, tablet_stats, versionstamp, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ if (err == TxnErrorCode::TXN_OK) {
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+ }
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_load_stats(
+ const std::vector<int64_t>& tablet_ids,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats,
+ std::unordered_map<int64_t, Versionstamp>* versionstamps, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_tablet_load_stats(txn.get(), tablet_ids, tablet_stats, versionstamps, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_load_stats(
+ Transaction* txn, const std::vector<int64_t>& tablet_ids,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats,
+ std::unordered_map<int64_t, Versionstamp>* versionstamps, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ std::vector<int64_t> remaining_ids = tablet_ids;
+
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ std::unordered_map<int64_t, TabletStatsPB> current_stats;
+ std::unordered_map<int64_t, Versionstamp> current_versionstamps;
+ TxnErrorCode err = reader.get_tablet_load_stats(txn, remaining_ids, ¤t_stats,
+ ¤t_versionstamps, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ min_read_versionstamp_ = std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+
+ // Add found results to output
+ if (tablet_stats) {
+ for (const auto& [tablet_id, stats] : current_stats) {
+ (*tablet_stats)[tablet_id] = stats;
+ }
+ }
+ if (versionstamps) {
+ for (const auto& [tablet_id, versionstamp] : current_versionstamps) {
+ (*versionstamps)[tablet_id] = versionstamp;
+ }
+ }
+
+ // Remove found ids from remaining_ids
+ std::vector<int64_t> new_remaining_ids;
+ for (int64_t tablet_id : remaining_ids) {
+ if (!current_stats.contains(tablet_id)) {
+ new_remaining_ids.push_back(tablet_id);
+ }
+ }
+ remaining_ids = std::move(new_remaining_ids);
+
+ // If all found or no more to search, break
+ if (remaining_ids.empty()) {
+ break;
+ }
+
+ // Try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain, remaining ids are not found
+ break;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+
+ return TxnErrorCode::TXN_OK;
+}
+
+TxnErrorCode CloneChainReader::get_tablet_compact_stats(int64_t tablet_id,
+ TabletStatsPB* tablet_stats,
+ Versionstamp* versionstamp, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_tablet_compact_stats(txn.get(), tablet_id, tablet_stats, versionstamp, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_compact_stats(Transaction* txn, int64_t tablet_id,
+ TabletStatsPB* tablet_stats,
+ Versionstamp* versionstamp, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err = reader.get_tablet_compact_stats(txn, tablet_id, tablet_stats,
+ versionstamp, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ if (err == TxnErrorCode::TXN_OK) {
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+ }
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_compact_stats(
+ const std::vector<int64_t>& tablet_ids,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats,
+ std::unordered_map<int64_t, Versionstamp>* versionstamps, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_tablet_compact_stats(txn.get(), tablet_ids, tablet_stats, versionstamps, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_compact_stats(
+ Transaction* txn, const std::vector<int64_t>& tablet_ids,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats,
+ std::unordered_map<int64_t, Versionstamp>* versionstamps, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ std::vector<int64_t> remaining_ids = tablet_ids;
+
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ std::unordered_map<int64_t, TabletStatsPB> current_stats;
+ std::unordered_map<int64_t, Versionstamp> current_versionstamps;
+ TxnErrorCode err = reader.get_tablet_compact_stats(txn, remaining_ids, ¤t_stats,
+ ¤t_versionstamps, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ min_read_versionstamp_ = std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+
+ // Add found results to output
+ if (tablet_stats) {
+ for (const auto& [tablet_id, stats] : current_stats) {
+ (*tablet_stats)[tablet_id] = stats;
+ }
+ }
+ if (versionstamps) {
+ for (const auto& [tablet_id, versionstamp] : current_versionstamps) {
+ (*versionstamps)[tablet_id] = versionstamp;
+ }
+ }
+
+ // Remove found ids from remaining_ids
+ std::vector<int64_t> new_remaining_ids;
+ for (int64_t tablet_id : remaining_ids) {
+ if (!current_stats.contains(tablet_id)) {
+ new_remaining_ids.push_back(tablet_id);
+ }
+ }
+ remaining_ids = std::move(new_remaining_ids);
+
+ // If all found or no more to search, break
+ if (remaining_ids.empty()) {
+ break;
+ }
+
+ // Try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain, remaining ids are not found
+ break;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+
+ return TxnErrorCode::TXN_OK;
+}
+
+TxnErrorCode CloneChainReader::get_tablet_merged_stats(int64_t tablet_id,
+ TabletStatsPB* tablet_stats,
+ Versionstamp* versionstamp, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_tablet_merged_stats(txn.get(), tablet_id, tablet_stats, versionstamp, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_merged_stats(Transaction* txn, int64_t tablet_id,
+ TabletStatsPB* tablet_stats,
+ Versionstamp* versionstamp, bool snapshot) {
+ TabletStatsPB load_stats, compact_stats;
+ Versionstamp load_versionstamp, compact_versionstamp;
+
+ TxnErrorCode err =
+ get_tablet_load_stats(txn, tablet_id, &load_stats, &load_versionstamp, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ err = get_tablet_compact_stats(txn, tablet_id, &compact_stats, &compact_versionstamp, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+
+ MetaReader::merge_tablet_stats(load_stats, compact_stats, tablet_stats);
+ if (versionstamp) {
+ *versionstamp = std::min(load_versionstamp, compact_versionstamp);
+ }
+ return TxnErrorCode::TXN_OK;
+}
+
+TxnErrorCode CloneChainReader::get_tablet_index(int64_t tablet_id, TabletIndexPB* tablet_index,
+ bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_tablet_index(txn.get(), tablet_id, tablet_index, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_index(Transaction* txn, int64_t tablet_id,
+ TabletIndexPB* tablet_index, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err = reader.get_tablet_index(txn, tablet_id, tablet_index, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_indexes(
+ const std::vector<int64_t>& tablet_ids,
+ std::unordered_map<int64_t, TabletIndexPB>* tablet_indexes, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_tablet_indexes(txn.get(), tablet_ids, tablet_indexes, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_indexes(
+ Transaction* txn, const std::vector<int64_t>& tablet_ids,
+ std::unordered_map<int64_t, TabletIndexPB>* tablet_indexes, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ std::vector<int64_t> remaining_ids = tablet_ids;
+
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ std::unordered_map<int64_t, TabletIndexPB> current_indexes;
+ TxnErrorCode err =
+ reader.get_tablet_indexes(txn, remaining_ids, ¤t_indexes, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+
+ // Add found results to output
+ for (const auto& [tablet_id, index] : current_indexes) {
+ (*tablet_indexes)[tablet_id] = index;
+ }
+
+ // Remove found ids from remaining_ids
+ std::vector<int64_t> new_remaining_ids;
+ for (int64_t tablet_id : remaining_ids) {
+ if (!current_indexes.contains(tablet_id)) {
+ new_remaining_ids.push_back(tablet_id);
+ }
+ }
+ remaining_ids = std::move(new_remaining_ids);
+
+ // If all found or no more to search, break
+ if (remaining_ids.empty()) {
+ break;
+ }
+
+ // Try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain, remaining ids are not found
+ break;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+
+ return TxnErrorCode::TXN_OK;
+}
+
+TxnErrorCode CloneChainReader::get_tablet_meta(int64_t tablet_id, TabletMetaCloudPB* tablet_meta,
+ Versionstamp* versionstamp, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_tablet_meta(txn.get(), tablet_id, tablet_meta, versionstamp, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_meta(Transaction* txn, int64_t tablet_id,
+ TabletMetaCloudPB* tablet_meta,
+ Versionstamp* versionstamp, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err =
+ reader.get_tablet_meta(txn, tablet_id, tablet_meta, versionstamp, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ if (err == TxnErrorCode::TXN_OK) {
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+ }
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_schema(int64_t index_id, int64_t schema_version,
+ TabletSchemaCloudPB* tablet_schema,
+ bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_tablet_schema(txn.get(), index_id, schema_version, tablet_schema, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_tablet_schema(Transaction* txn, int64_t index_id,
+ int64_t schema_version,
+ TabletSchemaCloudPB* tablet_schema,
+ bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err =
+ reader.get_tablet_schema(txn, index_id, schema_version, tablet_schema, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_rowset_meta(int64_t tablet_id, int64_t end_version,
+ RowsetMetaCloudPB* rowset_meta, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_rowset_meta(txn.get(), tablet_id, end_version, rowset_meta, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_rowset_meta(Transaction* txn, int64_t tablet_id,
+ int64_t end_version, RowsetMetaCloudPB* rowset_meta,
+ bool snapshot) {
+ RowsetMetaCloudPB load_rowset_meta, compact_rowset_meta;
+ Versionstamp load_versionstamp, compact_versionstamp;
+
+ TxnErrorCode err = get_load_rowset_meta(txn, tablet_id, end_version, &load_rowset_meta,
+ &load_versionstamp, snapshot);
+ if (err != TxnErrorCode::TXN_OK && err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ return err;
+ }
+ bool load_rowset_exists = (err == TxnErrorCode::TXN_OK);
+
+ err = get_compact_rowset_meta(txn, tablet_id, end_version, &compact_rowset_meta,
+ &compact_versionstamp, snapshot);
+ if (err != TxnErrorCode::TXN_OK && err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ return err;
+ }
+ bool compact_rowset_exists = (err == TxnErrorCode::TXN_OK);
+
+ if (!load_rowset_exists && !compact_rowset_exists) {
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+
+ if (load_rowset_exists && !compact_rowset_exists) {
+ *rowset_meta = std::move(load_rowset_meta);
+ } else if (!load_rowset_exists && compact_rowset_exists) {
+ *rowset_meta = std::move(compact_rowset_meta);
+ } else if (load_versionstamp < compact_versionstamp) {
+ *rowset_meta = std::move(compact_rowset_meta);
+ } else {
+ *rowset_meta = std::move(load_rowset_meta);
+ }
+
+ return TxnErrorCode::TXN_OK;
+}
+
+TxnErrorCode CloneChainReader::get_rowset_metas(int64_t tablet_id, int64_t start_version,
+ int64_t end_version,
+ std::vector<RowsetMetaCloudPB>* rowset_metas,
+ bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_rowset_metas(txn.get(), tablet_id, start_version, end_version, rowset_metas,
+ snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_rowset_metas(Transaction* txn, int64_t tablet_id,
+ int64_t start_version, int64_t end_version,
+ std::vector<RowsetMetaCloudPB>* rowset_metas,
+ bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ std::map<int64_t, RowsetMetaCloudPB> version_to_rowset;
+
+ std::vector<std::pair<int64_t, int64_t>> searching_ranges;
+ searching_ranges.emplace_back(start_version, end_version);
+
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ for (auto& [start, end] : searching_ranges) {
+ std::vector<RowsetMetaCloudPB> current_rowsets;
+ TxnErrorCode err =
+ reader.get_rowset_metas(txn, tablet_id, start, end, ¤t_rowsets, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+
+ // Add found rowsets to version_to_rowset map (only if not already found)
+ for (auto&& rowset : current_rowsets) {
+ int64_t version = rowset.end_version();
+ if (version_to_rowset.contains(version)) {
+ LOG_WARNING("Duplicate rowset for version {} found in clone chain, ignoring",
+ version);
+ return TxnErrorCode::TXN_INVALID_DATA;
+ }
+ if (!rowset.has_reference_instance_id()) {
+ rowset.set_reference_instance_id(current_instance_id);
+ }
+ version_to_rowset[version] = std::move(rowset);
+ }
+ }
+
+ // There should be no overlapping ranges in version_to_rowset
+ searching_ranges.clear();
+
+ int64_t next_version = start_version;
+ for (auto&& [end_version, rowset] : version_to_rowset) {
+ if (end_version < next_version) {
+ LOG_WARNING("Overlapping rowset for version {} found in clone chain", end_version);
+ return TxnErrorCode::TXN_INVALID_DATA;
+ }
+ if (next_version != rowset.start_version()) {
+ // missing version range, need to search in previous clone chain
+ searching_ranges.emplace_back(next_version, rowset.start_version() - 1);
+ }
+ next_version = end_version + 1;
+ }
+ if (next_version <= end_version) {
+ // missing version range at the end
+ searching_ranges.emplace_back(next_version, end_version);
+ }
+
+ if (searching_ranges.empty()) {
+ // All versions found
+ break;
+ }
+
+ // Try to find missing versions in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain, break with what we found
+ break;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+
+ rowset_metas->clear();
+ rowset_metas->reserve(version_to_rowset.size());
+ for (auto&& [version, rowset] : version_to_rowset) {
+ rowset_metas->push_back(std::move(rowset));
+ }
+
+ return TxnErrorCode::TXN_OK;
+}
+
+TxnErrorCode CloneChainReader::get_load_rowset_meta(int64_t tablet_id, int64_t version,
+ RowsetMetaCloudPB* rowset_meta,
+ Versionstamp* versionstamp, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_load_rowset_meta(txn.get(), tablet_id, version, rowset_meta, versionstamp, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_load_rowset_meta(Transaction* txn, int64_t tablet_id,
+ int64_t version, RowsetMetaCloudPB* rowset_meta,
+ Versionstamp* versionstamp, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err = reader.get_load_rowset_meta(txn, tablet_id, version, rowset_meta,
+ versionstamp, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ if (err == TxnErrorCode::TXN_OK) {
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+ }
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_compact_rowset_meta(int64_t tablet_id, int64_t version,
+ RowsetMetaCloudPB* rowset_meta,
+ Versionstamp* versionstamp, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_compact_rowset_meta(txn.get(), tablet_id, version, rowset_meta, versionstamp,
+ snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_compact_rowset_meta(Transaction* txn, int64_t tablet_id,
+ int64_t version,
+ RowsetMetaCloudPB* rowset_meta,
+ Versionstamp* versionstamp, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err = reader.get_compact_rowset_meta(txn, tablet_id, version, rowset_meta,
+ versionstamp, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ if (err == TxnErrorCode::TXN_OK) {
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+ }
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_partition_pending_txn_id(int64_t partition_id,
+ int64_t* first_txn_id,
+ int64_t* partition_version,
+ bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_partition_pending_txn_id(txn.get(), partition_id, first_txn_id, partition_version,
+ snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_partition_pending_txn_id(Transaction* txn, int64_t partition_id,
+ int64_t* first_txn_id,
+ int64_t* partition_version,
+ bool snapshot) {
+ // Initialize to -1 to indicate no pending transactions
+ *first_txn_id = -1;
+
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+
+ VersionPB version_pb;
+ Versionstamp versionstamp;
+ TxnErrorCode err =
+ get_partition_version(txn, partition_id, &version_pb, &versionstamp, snapshot);
+ if (err == TxnErrorCode::TXN_OK) {
+ if (version_pb.pending_txn_ids_size() > 0) {
+ *first_txn_id = version_pb.pending_txn_ids(0);
+ }
+ *partition_version = version_pb.version();
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+ return TxnErrorCode::TXN_OK;
+ } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_OK;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_index_index(int64_t index_id, IndexIndexPB* index,
+ bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_index_index(txn.get(), index_id, index, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_index_index(Transaction* txn, int64_t index_id,
+ IndexIndexPB* index, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err = reader.get_index_index(txn, index_id, index, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_partition_index(int64_t partition_id,
+ PartitionIndexPB* partition_index,
+ bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_partition_index(txn.get(), partition_id, partition_index, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_partition_index(Transaction* txn, int64_t partition_id,
+ PartitionIndexPB* partition_index,
+ bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err = reader.get_partition_index(txn, partition_id, partition_index, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::is_index_exists(int64_t index_id, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return is_index_exists(txn.get(), index_id, snapshot);
+}
+
+TxnErrorCode CloneChainReader::is_index_exists(Transaction* txn, int64_t index_id, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err = reader.is_index_exists(txn, index_id, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ if (err == TxnErrorCode::TXN_OK) {
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+ }
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::is_partition_exists(int64_t partition_id, bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return is_partition_exists(txn.get(), partition_id, snapshot);
+}
+
+TxnErrorCode CloneChainReader::is_partition_exists(Transaction* txn, int64_t partition_id,
+ bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err = reader.is_partition_exists(txn, partition_id, snapshot);
+ if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ if (err == TxnErrorCode::TXN_OK) {
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+ }
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::has_no_indexes(int64_t db_id, int64_t table_id, bool* no_indexes,
+ bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return has_no_indexes(txn.get(), db_id, table_id, no_indexes, snapshot);
+}
+
+TxnErrorCode CloneChainReader::has_no_indexes(Transaction* txn, int64_t db_id, int64_t table_id,
+ bool* no_indexes, bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ Versionstamp current_snapshot_version = snapshot_version_;
+
+ bool local_no_indexes = true;
+ do {
+ MetaReader reader(current_instance_id, current_snapshot_version);
+ TxnErrorCode err = reader.has_no_indexes(txn, db_id, table_id, &local_no_indexes, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ } else if (!local_no_indexes) {
+ *no_indexes = false;
+ min_read_versionstamp_ =
+ std::min(reader.min_read_versionstamp(), min_read_versionstamp_);
+ return TxnErrorCode::TXN_OK;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ *no_indexes = true;
+ return TxnErrorCode::TXN_OK;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ current_snapshot_version = prev_snapshot_version;
+ } while (true);
+}
+
+TxnErrorCode CloneChainReader::get_delete_bitmap_v2(int64_t tablet_id, const std::string& rowset_id,
+ DeleteBitmapStoragePB* delete_bitmap,
+ bool snapshot) {
+ DCHECK(txn_kv_) << "TxnKv must be set before calling";
+ if (!txn_kv_) {
+ return TxnErrorCode::TXN_INVALID_ARGUMENT;
+ }
+
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_delete_bitmap_v2(txn.get(), tablet_id, rowset_id, delete_bitmap, snapshot);
+}
+
+TxnErrorCode CloneChainReader::get_delete_bitmap_v2(Transaction* txn, int64_t tablet_id,
+ const std::string& rowset_id,
+ DeleteBitmapStoragePB* delete_bitmap,
+ bool snapshot) {
+ std::string current_instance_id(instance_id_);
+ do {
+ std::string key =
+ versioned::meta_delete_bitmap_key({current_instance_id, tablet_id, rowset_id});
+ ValueBuf val_buf;
+ TxnErrorCode err = cloud::blob_get(txn, key, &val_buf);
+ if (err == TxnErrorCode::TXN_OK) {
+ if (!val_buf.to_pb(delete_bitmap)) {
+ return TxnErrorCode::TXN_INVALID_DATA;
+ }
+ return TxnErrorCode::TXN_OK;
+ } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ return err;
+ }
+
+ // not found, try to find in previous clone chain
+ std::string prev_instance_id;
+ Versionstamp prev_snapshot_version;
+ if (!get_source_snapshot_info(current_instance_id, &prev_instance_id,
+ &prev_snapshot_version)) {
+ // no previous clone chain
+ return TxnErrorCode::TXN_KEY_NOT_FOUND;
+ }
+ current_instance_id = std::move(prev_instance_id);
+ } while (true);
+}
+
+} // namespace doris::cloud
diff --git a/cloud/src/meta-store/meta_reader.h b/cloud/src/meta-store/clone_chain_reader.h
similarity index 70%
copy from cloud/src/meta-store/meta_reader.h
copy to cloud/src/meta-store/clone_chain_reader.h
index 3eb6ab51d7a..493812805ed 100644
--- a/cloud/src/meta-store/meta_reader.h
+++ b/cloud/src/meta-store/clone_chain_reader.h
@@ -18,35 +18,30 @@
#pragma once
#include <gen_cpp/cloud.pb.h>
-#include <gen_cpp/olap_file.pb.h>
#include "meta-store/txn_kv.h"
-#include "meta-store/txn_kv_error.h"
#include "meta-store/versionstamp.h"
namespace doris::cloud {
-// A versioned meta reader that encapsulates the logic to read versioned metadata.
-//
-// This class is lightweight and does not hold any state. So constructing multiple instances
-// is cheap and does not require any cleanup.
-//
-// But the caller should ensure that the referenced instance_id and txn_kv are valid
-// throughout the lifetime of the MetaReader instance.
-class MetaReader {
+class ResourceManager;
+
+class CloneChainReader {
public:
- MetaReader(std::string_view instance_id) : MetaReader(instance_id, nullptr) {}
- MetaReader(std::string_view instance_id, TxnKv* txn_kv)
- : MetaReader(instance_id, txn_kv, Versionstamp::max()) {}
- MetaReader(std::string_view instance_id, Versionstamp snapshot_version)
- : MetaReader(instance_id, nullptr, snapshot_version) {}
- MetaReader(std::string_view instance_id, TxnKv* txn_kv, Versionstamp snapshot_version)
+ CloneChainReader(std::string_view instance_id, ResourceManager* resource_mgr)
+ : CloneChainReader(instance_id, Versionstamp::max(), nullptr, resource_mgr) {}
+ CloneChainReader(std::string_view instance_id, Versionstamp snapshot_version,
+ ResourceManager* resource_mgr)
+ : CloneChainReader(instance_id, snapshot_version, nullptr, resource_mgr) {}
+ CloneChainReader(std::string_view instance_id, TxnKv* txn_kv, ResourceManager* resource_mgr)
+ : CloneChainReader(instance_id, Versionstamp::max(), txn_kv, resource_mgr) {}
+ CloneChainReader(std::string_view instance_id, Versionstamp snapshot_version, TxnKv* txn_kv,
+ ResourceManager* resource_mgr)
: instance_id_(instance_id),
snapshot_version_(snapshot_version),
txn_kv_(txn_kv),
+ resource_mgr_(resource_mgr),
min_read_versionstamp_(Versionstamp::max()) {}
- MetaReader(const MetaReader&) = delete;
- MetaReader& operator=(const MetaReader&) = delete;
uint64_t min_read_version() const { return min_read_versionstamp_.version(); }
Versionstamp min_read_versionstamp() const { return min_read_versionstamp_; }
@@ -108,6 +103,17 @@ public:
TabletStatsPB* tablet_stats, Versionstamp* versionstamp,
bool snapshot = false);
+ // Get the tablet load stats for the given tablet_ids (batch version).
+ // If a tablet_id does not exist, then it will not be included in the respective map.
+ TxnErrorCode get_tablet_load_stats(const std::vector<int64_t>& tablet_ids,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats,
+ std::unordered_map<int64_t, Versionstamp>* versionstamps,
+ bool snapshot = false);
+ TxnErrorCode get_tablet_load_stats(Transaction* txn, const std::vector<int64_t>& tablet_ids,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats,
+ std::unordered_map<int64_t, Versionstamp>* versionstamps,
+ bool snapshot = false);
+
// Get the tablet compact stats for the given tablet
//
// If the `tablet_stats` is not nullptr, it will be filled with the deserialized TabletStatsPB.
@@ -154,6 +160,17 @@ public:
std::unordered_map<int64_t, TabletIndexPB>* tablet_indexes,
bool snapshot = false);
+ // Get the rowset meta for the given tablet_id and end_version.
+ //
+ // It will compare the versionstamp of the load rowset and the compact rowset, and return the one
+ // with the higher versionstamp.
+ //
+ // It returns TXN_KEY_NOT_FOUND if no rowset meta is found for the given tablet_id and end_version.
+ TxnErrorCode get_rowset_meta(int64_t tablet_id, int64_t end_version,
+ RowsetMetaCloudPB* rowset_meta, bool snapshot = false);
+ TxnErrorCode get_rowset_meta(Transaction* txn, int64_t tablet_id, int64_t end_version,
+ RowsetMetaCloudPB* rowset_meta, bool snapshot = false);
+
// Get the rowset meta for the given tablet_id and version range [start_version, end_version].
//
// The `rowset_metas` will be filled with the RowsetMetaCloudPB for each version in the range,
@@ -167,29 +184,40 @@ public:
// Get the load rowset meta for the given tablet_id and version.
TxnErrorCode get_load_rowset_meta(int64_t tablet_id, int64_t version,
- RowsetMetaCloudPB* rowset_meta, bool snapshot = false);
+ RowsetMetaCloudPB* rowset_meta, bool snapshot = false) {
+ Versionstamp versionstamp;
+ return get_load_rowset_meta(tablet_id, version, rowset_meta, &versionstamp, snapshot);
+ }
TxnErrorCode get_load_rowset_meta(Transaction* txn, int64_t tablet_id, int64_t version,
- RowsetMetaCloudPB* rowset_meta, bool snapshot = false);
-
- // Get the load rowset metas for the given tablet_id.
- TxnErrorCode get_load_rowset_metas(
- int64_t tablet_id,
- std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>>* rowset_metas,
- bool snapshot = false);
- TxnErrorCode get_load_rowset_metas(
- Transaction* txn, int64_t tablet_id,
- std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>>* rowset_metas,
- bool snapshot = false);
-
- // Get the compact rowset metas for the given tablet_id.
- TxnErrorCode get_compact_rowset_metas(
- int64_t tablet_id,
- std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>>* rowset_metas,
- bool snapshot = false);
- TxnErrorCode get_compact_rowset_metas(
- Transaction* txn, int64_t tablet_id,
- std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>>* rowset_metas,
- bool snapshot = false);
+ RowsetMetaCloudPB* rowset_meta, bool snapshot = false) {
+ Versionstamp versionstamp;
+ return get_load_rowset_meta(txn, tablet_id, version, rowset_meta, &versionstamp, snapshot);
+ }
+ TxnErrorCode get_load_rowset_meta(int64_t tablet_id, int64_t version,
+ RowsetMetaCloudPB* rowset_meta, Versionstamp* versionstamp,
+ bool snapshot = false);
+ TxnErrorCode get_load_rowset_meta(Transaction* txn, int64_t tablet_id, int64_t version,
+ RowsetMetaCloudPB* rowset_meta, Versionstamp* versionstamp,
+ bool snapshot = false);
+
+ // Get the compact rowset meta for the given tablet_id and version.
+ TxnErrorCode get_compact_rowset_meta(int64_t tablet_id, int64_t version,
+ RowsetMetaCloudPB* rowset_meta, bool snapshot = false) {
+ Versionstamp versionstamp;
+ return get_compact_rowset_meta(tablet_id, version, rowset_meta, &versionstamp, snapshot);
+ }
+ TxnErrorCode get_compact_rowset_meta(Transaction* txn, int64_t tablet_id, int64_t version,
+ RowsetMetaCloudPB* rowset_meta, bool snapshot = false) {
+ Versionstamp versionstamp;
+ return get_compact_rowset_meta(txn, tablet_id, version, rowset_meta, &versionstamp,
+ snapshot);
+ }
+ TxnErrorCode get_compact_rowset_meta(int64_t tablet_id, int64_t version,
+ RowsetMetaCloudPB* rowset_meta, Versionstamp* versionstamp,
+ bool snapshot = false);
+ TxnErrorCode get_compact_rowset_meta(Transaction* txn, int64_t tablet_id, int64_t version,
+ RowsetMetaCloudPB* rowset_meta, Versionstamp* versionstamp,
+ bool snapshot = false);
// Get the tablet meta keys.
TxnErrorCode get_tablet_meta(int64_t tablet_id, TabletMetaCloudPB* tablet_meta,
@@ -222,7 +250,7 @@ public:
TxnErrorCode get_partition_pending_txn_id(int64_t partition_id, int64_t* first_txn_id,
int64_t* partition_version, bool snapshot = false);
TxnErrorCode get_partition_pending_txn_id(Transaction* txn, int64_t partition_id,
- int64_t* partition_version, int64_t* first_txn_id,
+ int64_t* first_txn_id, int64_t* partition_version,
bool snapshot = false);
// Get the index of the given index id.
@@ -246,28 +274,34 @@ public:
TxnErrorCode is_partition_exists(int64_t partition_id, bool snapshot = false);
TxnErrorCode is_partition_exists(Transaction* txn, int64_t partition_id, bool snapshot = false);
- // Get the snapshots.
- TxnErrorCode get_snapshots(Transaction* txn,
- std::vector<std::pair<SnapshotPB, Versionstamp>>* snapshots);
- TxnErrorCode get_snapshots(std::vector<std::pair<SnapshotPB, Versionstamp>>* snapshots);
-
- // Whether the snapshot has references.
- TxnErrorCode has_snapshot_references(Versionstamp snapshot_version, bool* has_references,
- bool snapshot = false);
- TxnErrorCode has_snapshot_references(Transaction* txn, Versionstamp snapshot_version,
- bool* has_references, bool snapshot = false);
-
// Whether the table has no indexes.
TxnErrorCode has_no_indexes(int64_t db_id, int64_t table_id, bool* no_indexes,
bool snapshot = false);
TxnErrorCode has_no_indexes(Transaction* txn, int64_t db_id, int64_t table_id, bool* no_indexes,
bool snapshot = false);
+ // Get the delete bitmap for the given tablet_id and rowset_id.
+ TxnErrorCode get_delete_bitmap_v2(int64_t tablet_id, const std::string& rowset_id,
+ DeleteBitmapStoragePB* delete_bitmap, bool snapshot = false);
+ TxnErrorCode get_delete_bitmap_v2(Transaction* txn, int64_t tablet_id,
+ const std::string& rowset_id,
+ DeleteBitmapStoragePB* delete_bitmap, bool snapshot = false);
+
private:
+ // Get the source snapshot info of the specified `instance_id`.
+ //
+ // Return false if there is no source snapshot info for the `instance_id`.
+ bool get_source_snapshot_info(const std::string& instance_id, std::string* source_instance_id,
+ Versionstamp* source_snapshot_version);
+
+ // The instance id this reader is working on
const std::string_view instance_id_;
+ // The snapshot version to read
const Versionstamp snapshot_version_;
-
+ // The txn kv to use for reading, optional.
TxnKv* txn_kv_;
+ // The resource manager to use for reading.
+ ResourceManager* resource_mgr_;
Versionstamp min_read_versionstamp_;
};
diff --git a/cloud/src/meta-store/keys.cpp b/cloud/src/meta-store/keys.cpp
index 91b9266c815..4c0a746f947 100644
--- a/cloud/src/meta-store/keys.cpp
+++ b/cloud/src/meta-store/keys.cpp
@@ -68,6 +68,8 @@ static const char* JOB_KEY_INFIX_RL_PROGRESS = "routine_load_progress
static const char* JOB_KEY_INFIX_STREAMING_JOB = "streaming_job";
static const char* JOB_KEY_INFIX_RESTORE_TABLET = "restore_tablet";
static const char* JOB_KEY_INFIX_RESTORE_ROWSET = "restore_rowset";
+static const char* JOB_KEY_INFIX_SNAPSHOT_DATA_MIGRATOR = "snapshot_data_migrator";
+static const char* JOB_KEY_INFIX_SNAPSHOT_CHAIN_COMPACTOR = "snapshot_chain_compactor";
static const char* COPY_JOB_KEY_INFIX = "job";
static const char* COPY_FILE_KEY_INFIX = "loading_file";
@@ -146,7 +148,8 @@ static void encode_prefix(const T& t, std::string* key) {
MetaDeleteBitmapInfo, MetaDeleteBitmapUpdateLockInfo, MetaPendingDeleteBitmapInfo, PartitionVersionKeyInfo,
RecycleIndexKeyInfo, RecyclePartKeyInfo, RecycleRowsetKeyInfo, RecycleTxnKeyInfo, RecycleStageKeyInfo,
StatsTabletKeyInfo, TableVersionKeyInfo, JobRestoreTabletKeyInfo, JobRestoreRowsetKeyInfo,
- JobTabletKeyInfo, JobRecycleKeyInfo, RLJobProgressKeyInfo, StreamingJobKeyInfo,
+ JobTabletKeyInfo, JobRecycleKeyInfo, JobSnapshotDataMigratorKeyInfo, JobSnapshotChainCompactorKeyInfo,
+ RLJobProgressKeyInfo, StreamingJobKeyInfo,
CopyJobKeyInfo, CopyFileKeyInfo, StorageVaultKeyInfo, MetaSchemaPBDictionaryInfo,
MowTabletJobInfo>);
@@ -183,6 +186,8 @@ static void encode_prefix(const T& t, std::string* key) {
encode_bytes(STATS_KEY_PREFIX, key);
} else if constexpr (std::is_same_v<T, JobTabletKeyInfo>
|| std::is_same_v<T, JobRecycleKeyInfo>
+ || std::is_same_v<T, JobSnapshotDataMigratorKeyInfo>
+ || std::is_same_v<T, JobSnapshotChainCompactorKeyInfo>
|| std::is_same_v<T, RLJobProgressKeyInfo>
|| std::is_same_v<T, StreamingJobKeyInfo>) {
encode_bytes(JOB_KEY_PREFIX, key);
@@ -459,6 +464,17 @@ void job_check_key(const JobRecycleKeyInfo& in, std::string* out) {
encode_bytes("check", out); // "check"
}
+void job_snapshot_data_migrator_key(const JobSnapshotDataMigratorKeyInfo& in, std::string* out) {
+ encode_prefix(in, out); // 0x01 "job" ${instance_id}
+ encode_bytes(JOB_KEY_INFIX_SNAPSHOT_DATA_MIGRATOR, out); // "snapshot_data_migrator"
+}
+
+void job_snapshot_chain_compactor_key(const JobSnapshotChainCompactorKeyInfo& in,
+ std::string* out) {
+ encode_prefix(in, out); // 0x01 "job" ${instance_id}
+ encode_bytes(JOB_KEY_INFIX_SNAPSHOT_CHAIN_COMPACTOR, out); // "snapshot_chain_compactor"
+}
+
void rl_job_progress_key_info(const RLJobProgressKeyInfo& in, std::string* out) {
encode_prefix(in, out); // 0x01 "job" ${instance_id}
encode_bytes(JOB_KEY_INFIX_RL_PROGRESS, out); // "routine_load_progress"
@@ -558,6 +574,16 @@ std::string system_meta_service_encryption_key_info_key() {
return ret;
}
+// 0x02 0:"system" 1:"meta-service" 2:"instance_update"
+std::string system_meta_service_instance_update_key() {
+ std::string ret;
+ ret.push_back(CLOUD_SYS_KEY_SPACE02);
+ encode_bytes("system", &ret);
+ encode_bytes("meta-service", &ret);
+ encode_bytes("instance_update", &ret);
+ return ret;
+}
+
//==============================================================================
// Other keys
//==============================================================================
@@ -612,6 +638,14 @@ std::string log_key_prefix(std::string_view instance_id) {
return out;
}
+std::string snapshot_key_prefix(std::string_view instance_id) {
+ std::string out;
+ out.push_back(CLOUD_VERSIONED_KEY_SPACE03);
+ encode_bytes(SNAPSHOT_KEY_PREFIX, &out); // "snapshot"
+ encode_bytes(instance_id, &out); // instance_id
+ return out;
+}
+
//==============================================================================
// Version keys
//==============================================================================
@@ -652,36 +686,6 @@ void partition_inverted_index_key(const PartitionInvertedIndexKeyInfo& in, std::
encode_int64(std::get<3>(in), out); // partition_id
}
-int decode_partition_inverted_index_key(std::string_view* in, int64_t* db_id, int64_t* table_id,
- int64_t* partition_id) {
- if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_VERSIONED_KEY_SPACE03) {
- return -1;
- }
-
- in->remove_prefix(1);
-
- // 0x03 "index" ${instance_id} "partition_inverted" ${db_id} ${table_id} ${partition}
- std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
- if (decode_key(in, &out) != 0 || out.size() != 6) {
- return -1;
- } else if (auto* ptr = std::get_if<std::string>(&std::get<0>(out[2]));
- ptr == nullptr || *ptr != PARTITION_INVERTED_INDEX_KEY_INFIX) {
- return -1;
- }
-
- auto* db_id_ptr = std::get_if<int64_t>(&std::get<0>(out[3]));
- auto* table_id_ptr = std::get_if<int64_t>(&std::get<0>(out[4]));
- auto* partition_id_ptr = std::get_if<int64_t>(&std::get<0>(out[5]));
- if (db_id_ptr == nullptr || table_id_ptr == nullptr || partition_id_ptr == nullptr) {
- return -1;
- }
-
- *db_id = *db_id_ptr;
- *table_id = *table_id_ptr;
- *partition_id = *partition_id_ptr;
- return 0;
-}
-
void tablet_index_key(const TabletIndexKeyInfo& in, std::string* out) {
out->push_back(CLOUD_VERSIONED_KEY_SPACE03);
encode_bytes(INDEX_KEY_PREFIX, out); // "index"
@@ -813,6 +817,15 @@ void data_rowset_ref_count_key(const DataRowsetRefCountKeyInfo& in, std::string*
encode_bytes(std::get<2>(in), out); // rowset_id
}
+void meta_rowset_key(const MetaRowsetKeyInfo& in, std::string* out) {
+ out->push_back(CLOUD_VERSIONED_KEY_SPACE03);
+ encode_bytes(META_KEY_PREFIX, out); // "meta"
+ encode_bytes(std::get<0>(in), out); // instance_id
+ encode_bytes(META_KEY_INFIX_ROWSET, out); // "rowset"
+ encode_int64(std::get<1>(in), out); // tablet_id
+ encode_bytes(std::get<2>(in), out); // rowset_id
+}
+
//==============================================================================
// Snapshot keys
//==============================================================================
@@ -842,6 +855,15 @@ std::string snapshot_reference_key_prefix(std::string_view instance_id, Versions
return out;
}
+std::string snapshot_reference_key_prefix(std::string_view instance_id) {
+ std::string out;
+ out.push_back(CLOUD_VERSIONED_KEY_SPACE03);
+ encode_bytes(SNAPSHOT_KEY_PREFIX, &out); // "snapshot"
+ encode_bytes(instance_id, &out); // instance_id
+ encode_bytes(SNAPSHOT_REFERENCE_KEY_INFIX, &out); // "reference"
+ return out;
+}
+
//==============================================================================
// Log keys
//==============================================================================
@@ -857,7 +879,8 @@ void log_key(const LogKeyInfo& in, std::string* out) {
// Decode keys
//==============================================================================
int decode_key(std::string_view* in,
- std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>>* out) {
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>>* out,
+ Versionstamp* timestamp) {
int pos = 0;
int last_len = static_cast<int>(in->size());
while (!in->empty()) {
@@ -874,6 +897,16 @@ int decode_key(std::string_view* in,
ret = decode_int64(in, &v);
if (ret != 0) return ret;
out->emplace_back(v, tag, pos);
+ } else if (tag == EncodingTag::VERSIONSTAMP_TAG) {
+ Versionstamp vs;
+ ret = decode_versionstamp(in, &vs);
+ if (ret != 0) return ret;
+ if (timestamp) {
+ *timestamp = vs;
+ }
+ ret = decode_tailing_versionstamp_end(in);
+ if (ret != 0) return ret;
+ out->emplace_back(vs.to_string(), tag, pos);
} else {
return -1;
}
@@ -910,4 +943,508 @@ std::vector<std::string> get_single_version_meta_key_prefixs() {
return key_prefix_list;
}
+namespace versioned {
+
+bool decode_table_version_key(std::string_view* in, int64_t* table_id, Versionstamp* timestamp) {
+ // 0x03 "version" ${instance_id} "table" ${table_id} ${timestamp}
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_VERSIONED_KEY_SPACE03) {
+ return false;
+ }
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ auto res = decode_key(in, &out, timestamp);
+ if (res != 0 || out.size() != 5) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != VERSION_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != TABLE_VERSION_KEY_INFIX) {
+ return false;
+ }
+ *table_id = std::get<int64_t>(std::get<0>(out[3]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+bool decode_partition_inverted_index_key(std::string_view* in, int64_t* db_id, int64_t* table_id,
+ int64_t* partition_id) {
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_VERSIONED_KEY_SPACE03) {
+ return false;
+ }
+
+ in->remove_prefix(1);
+
+ // 0x03 "index" ${instance_id} "partition_inverted" ${db_id} ${table_id} ${partition}
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ if (decode_key(in, &out) != 0 || out.size() != 6) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[2])) != PARTITION_INVERTED_INDEX_KEY_INFIX) {
+ return false;
+ }
+ *db_id = std::get<int64_t>(std::get<0>(out[3]));
+ *table_id = std::get<int64_t>(std::get<0>(out[4]));
+ *partition_id = std::get<int64_t>(std::get<0>(out[5]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+bool decode_meta_partition_key(std::string_view* in, int64_t* partition_id,
+ Versionstamp* timestamp) {
+ // 0x03 "meta" ${instance_id} "partition" ${partition_id} ${timestamp}
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_VERSIONED_KEY_SPACE03) {
+ return false;
+ }
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ auto res = decode_key(in, &out, timestamp);
+ if (res != 0 || out.size() != 5) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != META_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != META_PARTITION_KEY_INFIX) {
+ return false;
+ }
+ *partition_id = std::get<int64_t>(std::get<0>(out[3]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+bool decode_meta_index_key(std::string_view* in, int64_t* index_id, Versionstamp* timestamp) {
+ // 0x03 "meta" ${instance_id} "index" ${index_id} ${timestamp}
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_VERSIONED_KEY_SPACE03) {
+ return false;
+ }
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ auto res = decode_key(in, &out, timestamp);
+ if (res != 0 || out.size() != 5) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != META_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != META_INDEX_KEY_INFIX) {
+ return false;
+ }
+ *index_id = std::get<int64_t>(std::get<0>(out[3]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+bool decode_meta_schema_key(std::string_view* in, int64_t* index_id, int64_t* schema_version) {
+ // 0x03 "meta" ${instance_id} "schema" ${index_id} ${schema_version}
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_VERSIONED_KEY_SPACE03) {
+ return false;
+ }
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ auto res = decode_key(in, &out);
+ if (res != 0 || out.size() < 5) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != META_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != META_KEY_INFIX_SCHEMA) {
+ return false;
+ }
+ *index_id = std::get<int64_t>(std::get<0>(out[3]));
+ *schema_version = std::get<int64_t>(std::get<0>(out[4]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+bool decode_meta_tablet_key(std::string_view* in, int64_t* tablet_id, Versionstamp* timestamp) {
+ // 0x03 "meta" ${instance_id} "tablet" ${tablet_id} ${timestamp}
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_VERSIONED_KEY_SPACE03) {
+ return false;
+ }
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ auto res = decode_key(in, &out, timestamp);
+ if (res != 0 || out.size() < 5) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != META_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != META_KEY_INFIX_TABLET) {
+ return false;
+ }
+ *tablet_id = std::get<int64_t>(std::get<0>(out[3]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+// Decode tablet inverted index key
+// Return true if decode successfully, otherwise false
+bool decode_tablet_inverted_index_key(std::string_view* in, int64_t* db_id, int64_t* table_id,
+ int64_t* index_id, int64_t* partition_id,
+ int64_t* tablet_id) {
+ // 0x03 "index" ${instance_id} "tablet_inverted" ${db_id} ${table_id} ${index_id} ${partition} ${tablet}
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_VERSIONED_KEY_SPACE03) {
+ return false;
+ }
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ auto res = decode_key(in, &out);
+ if (res != 0 || out.size() != 8) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != INDEX_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != TABLET_INVERTED_INDEX_KEY_INFIX) {
+ return false;
+ }
+ *db_id = std::get<int64_t>(std::get<0>(out[3]));
+ *table_id = std::get<int64_t>(std::get<0>(out[4]));
+ *index_id = std::get<int64_t>(std::get<0>(out[5]));
+ *partition_id = std::get<int64_t>(std::get<0>(out[6]));
+ *tablet_id = std::get<int64_t>(std::get<0>(out[7]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+bool decode_snapshot_ref_key(std::string_view* in, std::string* instance_id,
+ Versionstamp* timestamp, std::string* ref_instance_id) {
+ // Key format: 0x03 + encode_bytes("snapshot") + encode_bytes(instance_id) +
+ // encode_bytes("reference") + encode_versionstamp(timestamp) + encode_bytes(ref_instance_id)
+
+ if (in->empty() || (*in)[0] != CLOUD_VERSIONED_KEY_SPACE03) {
+ return false;
+ }
+ in->remove_prefix(1);
+
+ // Decode "snapshot"
+ std::string snapshot_prefix;
+ if (decode_bytes(in, &snapshot_prefix) != 0 || snapshot_prefix != SNAPSHOT_KEY_PREFIX) {
+ return false;
+ }
+
+ // Decode instance_id
+ if (instance_id && decode_bytes(in, instance_id) != 0) {
+ return false;
+ } else if (!instance_id) {
+ std::string dummy;
+ if (decode_bytes(in, &dummy) != 0) {
+ return false;
+ }
+ }
+
+ // Decode "reference"
+ std::string reference_infix;
+ if (decode_bytes(in, &reference_infix) != 0 ||
+ reference_infix != SNAPSHOT_REFERENCE_KEY_INFIX) {
+ return false;
+ }
+
+ // Decode versionstamp (10 bytes)
+ if (timestamp && decode_versionstamp(in, timestamp) != 0) {
+ return false;
+ } else if (!timestamp) {
+ Versionstamp dummy;
+ if (decode_versionstamp(in, &dummy) != 0) {
+ return false;
+ }
+ }
+
+ // Decode ref_instance_id
+ if (ref_instance_id && decode_bytes(in, ref_instance_id) != 0) {
+ return false;
+ }
+
+ return true;
+}
+
+bool decode_data_rowset_ref_count_key(std::string_view* in, int64_t* tablet_id,
+ std::string* rowset_id) {
+ // 0x03 "data" ${instance_id} "rowset_ref_count" ${tablet_id} ${rowset_id}
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_VERSIONED_KEY_SPACE03) {
+ return false;
+ }
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ auto res = decode_key(in, &out);
+ if (res != 0 || out.size() != 5) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != DATA_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != META_ROWSET_REF_COUNT_KEY_INFIX) {
+ return false;
+ }
+ *tablet_id = std::get<int64_t>(std::get<0>(out[3]));
+ *rowset_id = std::get<std::string>(std::get<0>(out[4]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+} // namespace versioned
+
+// Decode stats tablet key to extract table_id, index_id, partition_id and tablet_id
+// 0x01 "stats" ${instance_id} "tablet" ${table_id} ${index_id} ${partition_id} ${tablet_id}
+bool decode_stats_tablet_key(std::string_view* in, int64_t* table_id, int64_t* index_id,
+ int64_t* partition_id, int64_t* tablet_id) {
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_USER_KEY_SPACE01) {
+ return false;
+ }
+
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ if (decode_key(in, &out) != 0 || out.size() != 7) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != STATS_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != STATS_KEY_INFIX_TABLET) {
+ return false;
+ }
+ *table_id = std::get<int64_t>(std::get<0>(out[3]));
+ *index_id = std::get<int64_t>(std::get<0>(out[4]));
+ *partition_id = std::get<int64_t>(std::get<0>(out[5]));
+ *tablet_id = std::get<int64_t>(std::get<0>(out[6]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+// Decode table version key to extract db_id and tbl_id
+// 0x01 "version" ${instance_id} "table" ${db_id} ${tbl_id}
+bool decode_table_version_key(std::string_view* in, int64_t* db_id, int64_t* tbl_id) {
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_USER_KEY_SPACE01) {
+ return false;
+ }
+
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ if (decode_key(in, &out) != 0 || out.size() != 5) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != VERSION_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != TABLE_VERSION_KEY_INFIX) {
+ return false;
+ }
+ *db_id = std::get<int64_t>(std::get<0>(out[3]));
+ *tbl_id = std::get<int64_t>(std::get<0>(out[4]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+// Decode tablet schema key to extract index_id and schema_version
+// 0x01 "meta" ${instance_id} "schema" ${index_id} ${schema_version}
+bool decode_tablet_schema_key(std::string_view* in, int64_t* index_id, int64_t* schema_version) {
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_USER_KEY_SPACE01) {
+ return false;
+ }
+
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ if (decode_key(in, &out) != 0 || out.size() != 5) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != META_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != META_KEY_INFIX_SCHEMA) {
+ return false;
+ }
+ *index_id = std::get<int64_t>(std::get<0>(out[3]));
+ *schema_version = std::get<int64_t>(std::get<0>(out[4]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+// Decode partition version key to extract db_id, tbl_id and partition_id
+// 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
+bool decode_partition_version_key(std::string_view* in, int64_t* db_id, int64_t* tbl_id,
+ int64_t* partition_id) {
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_USER_KEY_SPACE01) {
+ return false;
+ }
+
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ if (decode_key(in, &out) != 0 || out.size() != 6) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != VERSION_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != PARTITION_VERSION_KEY_INFIX) {
+ return false;
+ }
+ *db_id = std::get<int64_t>(std::get<0>(out[3]));
+ *tbl_id = std::get<int64_t>(std::get<0>(out[4]));
+ *partition_id = std::get<int64_t>(std::get<0>(out[5]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+// Decode meta tablet key to extract table_id, index_id, partition_id and tablet_id
+// 0x01 "meta" ${instance_id} "tablet" ${table_id} ${index_id} ${partition_id} ${tablet_id}
+bool decode_meta_tablet_key(std::string_view* in, int64_t* table_id, int64_t* index_id,
+ int64_t* partition_id, int64_t* tablet_id) {
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_USER_KEY_SPACE01) {
+ return false;
+ }
+
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ if (decode_key(in, &out) != 0 || out.size() != 7) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != META_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != META_KEY_INFIX_TABLET) {
+ return false;
+ }
+ *table_id = std::get<int64_t>(std::get<0>(out[3]));
+ *index_id = std::get<int64_t>(std::get<0>(out[4]));
+ *partition_id = std::get<int64_t>(std::get<0>(out[5]));
+ *tablet_id = std::get<int64_t>(std::get<0>(out[6]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+// Decode meta rowset key to extract tablet_id and version
+// 0x01 "meta" ${instance_id} "rowset" ${tablet_id} ${version}
+bool decode_meta_rowset_key(std::string_view* in, int64_t* tablet_id, int64_t* version) {
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_USER_KEY_SPACE01) {
+ return false;
+ }
+
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ if (decode_key(in, &out) != 0 || out.size() != 5) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != META_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != META_KEY_INFIX_ROWSET) {
+ return false;
+ }
+ *tablet_id = std::get<int64_t>(std::get<0>(out[3]));
+ *version = std::get<int64_t>(std::get<0>(out[4]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+// Decode meta tablet index key to extract tablet_id
+// 0x01 "meta" ${instance_id} "tablet_index" ${tablet_id}
+bool decode_meta_tablet_idx_key(std::string_view* in, int64_t* tablet_id) {
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_USER_KEY_SPACE01) {
+ return false;
+ }
+
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ if (decode_key(in, &out) != 0 || out.size() != 4) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != META_KEY_PREFIX ||
+ std::get<std::string>(std::get<0>(out[2])) != META_KEY_INFIX_TABLET_IDX) {
+ return false;
+ }
+ *tablet_id = std::get<int64_t>(std::get<0>(out[3]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
+// Decode instance key
+bool decode_instance_key(std::string_view* in, std::string* instance_id) {
+ if (in->empty() || static_cast<uint8_t>((*in)[0]) != CLOUD_USER_KEY_SPACE01) {
+ return false;
+ }
+
+ in->remove_prefix(1);
+
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
+ if (decode_key(in, &out) != 0 || out.size() != 2) {
+ return false;
+ }
+
+ try {
+ if (std::get<std::string>(std::get<0>(out[0])) != INSTANCE_KEY_PREFIX) {
+ return false;
+ }
+ *instance_id = std::get<std::string>(std::get<0>(out[1]));
+ } catch (const std::bad_variant_access& e) {
+ return false;
+ }
+
+ return true;
+}
+
} // namespace doris::cloud
diff --git a/cloud/src/meta-store/keys.h b/cloud/src/meta-store/keys.h
index 020702982d7..2f4e29e310c 100644
--- a/cloud/src/meta-store/keys.h
+++ b/cloud/src/meta-store/keys.h
@@ -66,8 +66,9 @@
// 0x01 "job" ${instance_id} "tablet" ${table_id} ${index_id} ${partition_id} ${tablet_id} -> TabletJobInfoPB
// 0x01 "job" ${instance_id} "recycle" -> JobRecyclePB
// 0x01 "job" ${instance_id} "check" -> JobRecyclePB
+// 0x01 "job" ${instance_id} "snapshot_data_migrator" -> JobRecyclePB
+// 0x01 "job" ${instance_id} "snapshot_chain_compactor" -> JobRecyclePB
// 0x01 "job" ${instance_id} "streaming_job" ${db_id} ${job_id} -> StreamingJobPB
-
//
// 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id} -> CopyJobPB
// 0x01 "copy" ${instance_id} "loading_file" ${stage_id} ${table_id} ${obj_name} ${etag} -> CopyFilePB
@@ -80,6 +81,7 @@
// 0x02 "system" "meta-service" "registry" -> MetaServiceRegistryPB
// 0x02 "system" "meta-service" "arn_info" -> RamUserPB
// 0x02 "system" "meta-service" "encryption_key_info" -> EncryptionKeyInfoPB
+// 0x02 "system" "meta-service" "instance_update" -> int64
//
// 0x03 "version" ${instance_id} "partition" ${partition_id} ${timestamp} -> VersionPB
// 0x03 "version" ${instance_id} "table" ${table_id} ${timestamp} -> ${empty_value}
@@ -100,6 +102,7 @@
// 0x03 "meta" ${instance_id} "schema" ${index_id} ${schema_version} -> TabletSchemaPB
// 0x03 "meta" ${instance_id} "rowset_load" ${tablet_id} ${version} ${timestamp} -> RowsetMetaPB
// 0x03 "meta" ${instance_id} "rowset_compact" ${tablet_id} ${version} ${timestamp} -> RowsetMetaPB
+// 0x03 "meta" ${instance_id} "delete_bitmap" ${tablet_id} ${rowset_id} -> DeleteBitmapStoragePB
//
// 0x03 "data" ${instance_id} "rowset_ref_count" ${tablet_id} ${rowset_id} => int64
//
@@ -145,93 +148,98 @@ struct BasicKeyInfo : Base {
// ATTN: newly added key must have different type number
// 0:instance_id
-using InstanceKeyInfo = BasicKeyInfo<0 , std::tuple<std::string>>;
+using InstanceKeyInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string>>;
// 0:instance_id 1:db_id 2:label
-using TxnLabelKeyInfo = BasicKeyInfo<1 , std::tuple<std::string, int64_t, std::string>>;
+using TxnLabelKeyInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t, std::string>>;
// 0:instance_id 1:db_id 2:txn_id
-using TxnInfoKeyInfo = BasicKeyInfo<2 , std::tuple<std::string, int64_t, int64_t>>;
+using TxnInfoKeyInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t, int64_t>>;
// 0:instance_id 1:txn_id
-using TxnIndexKeyInfo = BasicKeyInfo<3 , std::tuple<std::string, int64_t>>;
+using TxnIndexKeyInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t>>;
// 0:instance_id 1:db_id 2:txn_id
-using TxnRunningKeyInfo = BasicKeyInfo<5 , std::tuple<std::string, int64_t, int64_t>>;
+using TxnRunningKeyInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t, int64_t>>;
// 0:instance_id 1:db_id 2:tbl_id 3:partition_id
-using PartitionVersionKeyInfo = BasicKeyInfo<6 , std::tuple<std::string, int64_t, int64_t, int64_t>>;
+using PartitionVersionKeyInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t, int64_t, int64_t>>;
// 0:instance_id 1:tablet_id 2:version
-using MetaRowsetKeyInfo = BasicKeyInfo<7 , std::tuple<std::string, int64_t, int64_t>>;
+using MetaRowsetKeyInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t, int64_t>>;
// 0:instance_id 1:txn_id 2:tablet_id
-using MetaRowsetTmpKeyInfo = BasicKeyInfo<8 , std::tuple<std::string, int64_t, int64_t>>;
+using MetaRowsetTmpKeyInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t, int64_t>>;
// 0:instance_id 1:table_id 2:index_id 3:part_id 4:tablet_id
-using MetaTabletKeyInfo = BasicKeyInfo<9 , std::tuple<std::string, int64_t, int64_t, int64_t, int64_t>>;
+using MetaTabletKeyInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t, int64_t, int64_t, int64_t>>;
// 0:instance_id 1:tablet_id
-using MetaTabletIdxKeyInfo = BasicKeyInfo<10, std::tuple<std::string, int64_t>>;
+using MetaTabletIdxKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0:instance_id 1:index_id
-using RecycleIndexKeyInfo = BasicKeyInfo<11, std::tuple<std::string, int64_t>>;
+using RecycleIndexKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0:instance_id 1:part_id
-using RecyclePartKeyInfo = BasicKeyInfo<12, std::tuple<std::string, int64_t>>;
+using RecyclePartKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0:instance_id 1:tablet_id 2:rowset_id
-using RecycleRowsetKeyInfo = BasicKeyInfo<13, std::tuple<std::string, int64_t, std::string>>;
+using RecycleRowsetKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, std::string>>;
// 0:instance_id 1:db_id 2:txn_id
-using RecycleTxnKeyInfo = BasicKeyInfo<14, std::tuple<std::string, int64_t, int64_t>>;
+using RecycleTxnKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t>>;
// 0:instance_id 1:table_id 2:index_id 3:part_id 4:tablet_id
-using StatsTabletKeyInfo = BasicKeyInfo<15, std::tuple<std::string, int64_t, int64_t, int64_t, int64_t>>;
+using StatsTabletKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t, int64_t, int64_t>>;
// 0:instance_id 1:table_id 2:index_id 3:part_id 4:tablet_id
-using JobTabletKeyInfo = BasicKeyInfo<16, std::tuple<std::string, int64_t, int64_t, int64_t, int64_t>>;
+using JobTabletKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t, int64_t, int64_t>>;
// 0:instance_id 1:stage_id 2:table_id 3:copy_id 4:group_id
-using CopyJobKeyInfo = BasicKeyInfo<17, std::tuple<std::string, std::string, int64_t, std::string, int64_t>>;
+using CopyJobKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, std::string, int64_t, std::string, int64_t>>;
// 0:instance_id 1:stage_id 2:table_id 3:obj_key 4:obj_etag
-using CopyFileKeyInfo = BasicKeyInfo<18, std::tuple<std::string, std::string, int64_t, std::string, std::string>>;
+using CopyFileKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, std::string, int64_t, std::string, std::string>>;
// 0:instance_id 1:stage_id
-using RecycleStageKeyInfo = BasicKeyInfo<19, std::tuple<std::string, std::string>>;
+using RecycleStageKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, std::string>>;
+
+// 0:instance_id
+using JobRecycleKeyInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string>>;
// 0:instance_id
-using JobRecycleKeyInfo = BasicKeyInfo<20 , std::tuple<std::string>>;
+using JobSnapshotDataMigratorKeyInfo = BasicKeyInfo<53, std::tuple<std::string>>;
+// 0:instance_id
+using JobSnapshotChainCompactorKeyInfo = BasicKeyInfo<54, std::tuple<std::string>>;
// 0:instance_id 1:index_id 2:schema_version
-using MetaSchemaKeyInfo = BasicKeyInfo<21, std::tuple<std::string, int64_t, int64_t>>;
+using MetaSchemaKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t>>;
// 0:instance_id 1:tablet_id 2:rowest_id 3:version 4:seg_id
-using MetaDeleteBitmapInfo = BasicKeyInfo<22 , std::tuple<std::string, int64_t, std::string, int64_t, int64_t>>;
+using MetaDeleteBitmapInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t, std::string, int64_t, int64_t>>;
// partition_id of -1 indicates all partitions
// 0:instance_id 1:table_id 2:partition_id
-using MetaDeleteBitmapUpdateLockInfo = BasicKeyInfo<23 , std::tuple<std::string, int64_t, int64_t>>;
+using MetaDeleteBitmapUpdateLockInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t, int64_t>>;
// 0:instance_id 1:tablet_id
-using MetaPendingDeleteBitmapInfo = BasicKeyInfo<24 , std::tuple<std::string, int64_t>>;
+using MetaPendingDeleteBitmapInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t>>;
// 0:instance_id 1:db_id 2:job_id
-using RLJobProgressKeyInfo = BasicKeyInfo<25, std::tuple<std::string, int64_t, int64_t>>;
+using RLJobProgressKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t>>;
// 0:instance_id 1:db_id 2:job_id
-using StreamingJobKeyInfo = BasicKeyInfo<52, std::tuple<std::string, int64_t, int64_t>>;
+using StreamingJobKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t>>;
// 0:instance_id 1:vault_id
-using StorageVaultKeyInfo = BasicKeyInfo<26, std::tuple<std::string, std::string>>;
+using StorageVaultKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, std::string>>;
// 0:instance_id 1:db_id 2:table_id
-using TableVersionKeyInfo = BasicKeyInfo<27, std::tuple<std::string, int64_t, int64_t>>;
+using TableVersionKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t>>;
// 0:instance_id 1:index_id
-using MetaSchemaPBDictionaryInfo = BasicKeyInfo<28 , std::tuple<std::string, int64_t>>;
+using MetaSchemaPBDictionaryInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t>>;
// 0:instance_id 1:table_id 2:initiator
-using MowTabletJobInfo = BasicKeyInfo<29 , std::tuple<std::string, int64_t, int64_t>>;
+using MowTabletJobInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t, int64_t>>;
namespace versioned {
@@ -240,94 +248,98 @@ namespace versioned {
// 0x03 "version" ${instance_id} "partition" ${partition_id} ${timestamp} -> VersionPB
// 0:instance_id 1:partition_id
-using PartitionVersionKeyInfo = BasicKeyInfo<30, std::tuple<std::string, int64_t>>;
+using PartitionVersionKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0x03 "version" ${instance_id} "table" ${table_id} ${timestamp} -> ${empty_value}
// 0:instance_id 1:table_id
-using TableVersionKeyInfo = BasicKeyInfo<31, std::tuple<std::string, int64_t>>;
+using TableVersionKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0x03 "index" ${instance_id} "partition" ${partition_id} -> PartitionIndexPB
// 0:instance_id 1:partition_id
-using PartitionIndexKeyInfo = BasicKeyInfo<32, std::tuple<std::string, int64_t>>;
+using PartitionIndexKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0x03 "index" ${instance_id} "partition_inverted" ${db_id} ${table_id} ${partition} -> ${empty_value}
// 0:instance_id 1:db_id 2:table_id 3:partition_id
-using PartitionInvertedIndexKeyInfo = BasicKeyInfo<33, std::tuple<std::string, int64_t, int64_t, int64_t>>;
+using PartitionInvertedIndexKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t, int64_t>>;
// 0x03 "index" ${instance_id} "tablet" ${tablet_id} -> TabletIndexPB
// 0:instance_id 1:tablet_id
-using TabletIndexKeyInfo = BasicKeyInfo<34, std::tuple<std::string, int64_t>>;
+using TabletIndexKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0x03 "index" ${instance_id} "tablet_inverted" ${db_id} ${table_id} ${index_id} ${partition} ${tablet} -> ${empty_value}
// 0:instance_id 1:db_id 2:table_id 3:index_id 4:partition_id 5:tablet_id
-using TabletInvertedIndexKeyInfo = BasicKeyInfo<35, std::tuple<std::string, int64_t, int64_t, int64_t, int64_t, int64_t>>;
+using TabletInvertedIndexKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t, int64_t, int64_t, int64_t>>;
// 0x03 "index" ${instance_id} "index" ${index_id} -> IndexIndexPB
// 0:instance_id 1:index_id
-using IndexIndexKeyInfo = BasicKeyInfo<36, std::tuple<std::string, int64_t>>;
+using IndexIndexKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0x03 "index" ${instance_id} "index_inverted" ${db_id} ${table_id} ${index_id} -> ${empty_value}
// 0:instance_id 1:db_id 2:table_id 3:index_id
-using IndexInvertedKeyInfo = BasicKeyInfo<37, std::tuple<std::string, int64_t, int64_t, int64_t>>;
+using IndexInvertedKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t, int64_t>>;
// 0x03 "stats" ${instance_id} "tablet_load" ${tablet_id} ${timestamp} -> TabletStatsPB
// 0:instance_id 1:tablet_id
-using TabletLoadStatsKeyInfo = BasicKeyInfo<38, std::tuple<std::string, int64_t>>;
+using TabletLoadStatsKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0x03 "stats" ${instance_id} "tablet_compact" ${tablet_id} ${timestamp} -> TabletStatsPB
// 0:instance_id 1:tablet_id
-using TabletCompactStatsKeyInfo = BasicKeyInfo<39, std::tuple<std::string, int64_t>>;
+using TabletCompactStatsKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0x03 "meta" ${instance_id} "partition" ${partition_id} ${timestamp} -> ${empty_value}
// 0:instance_id 1:partition_id
-using MetaPartitionKeyInfo = BasicKeyInfo<40, std::tuple<std::string, int64_t>>;
+using MetaPartitionKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0x03 "meta" ${instance_id} "index" ${index_id} ${timestamp} -> ${empty_value}
// 0:instance_id 1:index_id
-using MetaIndexKeyInfo = BasicKeyInfo<41, std::tuple<std::string, int64_t>>;
+using MetaIndexKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0x03 "meta" ${instance_id} "tablet" ${tablet_id} ${timestamp} -> TabletMetaPB
// 0:instance_id 1:tablet_id
-using MetaTabletKeyInfo = BasicKeyInfo<42, std::tuple<std::string, int64_t>>;
+using MetaTabletKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0x03 "meta" ${instance_id} "schema" ${index_id} ${schema_version} -> TabletSchemaPB
// 0:instance_id 1:index_id 2:schema_version
-using MetaSchemaKeyInfo = BasicKeyInfo<43, std::tuple<std::string, int64_t, int64_t>>;
+using MetaSchemaKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t>>;
// 0x03 "meta" ${instance_id} "rowset_load" ${tablet_id} ${version} ${timestamp} -> RowsetMetaPB
// 0:instance_id 1:tablet_id 2:version
-using MetaRowsetLoadKeyInfo = BasicKeyInfo<44, std::tuple<std::string, int64_t, int64_t>>;
+using MetaRowsetLoadKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t>>;
// 0x03 "meta" ${instance_id} "rowset_compact" ${tablet_id} ${version} ${timestamp} -> RowsetMetaPB
// 0:instance_id 1:tablet_id 2:version
-using MetaRowsetCompactKeyInfo = BasicKeyInfo<45, std::tuple<std::string, int64_t, int64_t>>;
+using MetaRowsetCompactKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t>>;
// 0x03 "meta" ${instance_id} "delete_bitmap" ${tablet_id} ${rowset_id} -> DeleteBitmapStoragePB
// 0:instance_id 1:tablet_id 2:rowest_id
-using MetaDeleteBitmapInfo = BasicKeyInfo<22 , std::tuple<std::string, int64_t, std::string>>;
+using MetaDeleteBitmapInfo = BasicKeyInfo<__LINE__ , std::tuple<std::string, int64_t, std::string>>;
// 0x03 "data" ${instance_id} "rowset_ref_count" ${tablet_id} ${rowset_id} -> int64
// 0:instance_id 1:tablet_id 2:rowset_id
-using DataRowsetRefCountKeyInfo = BasicKeyInfo<46, std::tuple<std::string, int64_t, std::string>>;
+using DataRowsetRefCountKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, std::string>>;
+
+// 0x03 "meta" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RowsetMetaPB
+// 0:instance_id 1:tablet_id 2:rowset_id
+using MetaRowsetKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, std::string>>;
// 0x03 "snapshot" ${instance_id} "full" ${timestamp} -> SnapshotPB
// 0:instance_id
-using SnapshotFullKeyInfo = BasicKeyInfo<47, std::tuple<std::string>>;
+using SnapshotFullKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string>>;
// 0x03 "snapshot" ${instance_id} "reference" ${timestamp} ${instance_id} -> ${empty_value}
// 0:instance_id 1:timestamp 2:ref_instance_id
-using SnapshotReferenceKeyInfo = BasicKeyInfo<48, std::tuple<std::string, Versionstamp, std::string>>;
+using SnapshotReferenceKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, Versionstamp, std::string>>;
// 0x03 "log" ${instance_id} ${timestamp} -> OperationLogPB
// 0:instance_id
-using LogKeyInfo = BasicKeyInfo<49, std::tuple<std::string>>;
+using LogKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string>>;
} // namespace versioned
// 0:instance_id 1:tablet_id
-using JobRestoreTabletKeyInfo = BasicKeyInfo<50, std::tuple<std::string, int64_t>>;
+using JobRestoreTabletKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t>>;
// 0:instance_id 1:tablet_id 2:version
-using JobRestoreRowsetKeyInfo = BasicKeyInfo<51, std::tuple<std::string, int64_t, int64_t>>;
+using JobRestoreRowsetKeyInfo = BasicKeyInfo<__LINE__, std::tuple<std::string, int64_t, int64_t>>;
void instance_key(const InstanceKeyInfo& in, std::string* out);
static inline std::string instance_key(const InstanceKeyInfo& in) { std::string s; instance_key(in, &s); return s; }
@@ -407,7 +419,11 @@ static inline std::string job_restore_rowset_key(const JobRestoreRowsetKeyInfo&
void job_recycle_key(const JobRecycleKeyInfo& in, std::string* out);
void job_check_key(const JobRecycleKeyInfo& in, std::string* out);
+void job_snapshot_data_migrator_key(const JobSnapshotDataMigratorKeyInfo& in, std::string* out);
+void job_snapshot_chain_compactor_key(const JobSnapshotChainCompactorKeyInfo& in, std::string* out);
static inline std::string job_check_key(const JobRecycleKeyInfo& in) { std::string s; job_check_key(in, &s); return s; }
+static inline std::string job_snapshot_data_migrator_key(const JobSnapshotDataMigratorKeyInfo& in) { std::string s; job_snapshot_data_migrator_key(in, &s); return s; }
+static inline std::string job_snapshot_chain_compactor_key(const JobSnapshotChainCompactorKeyInfo& in) { std::string s; job_snapshot_chain_compactor_key(in, &s); return s; }
void job_tablet_key(const JobTabletKeyInfo& in, std::string* out);
static inline std::string job_tablet_key(const JobTabletKeyInfo& in) { std::string s; job_tablet_key(in, &s); return s; }
void rl_job_progress_key_info(const RLJobProgressKeyInfo& in, std::string* out);
@@ -423,6 +439,7 @@ void copy_file_key(const CopyFileKeyInfo& in, std::string* out);
std::string system_meta_service_registry_key();
std::string system_meta_service_arn_info_key();
+std::string system_meta_service_instance_update_key();
// Note:
// This key points to a value (EncryptionKeyInfoPB, the format is below) which stores a set of items,
@@ -450,6 +467,7 @@ std::string stats_key_prefix(std::string_view instance_id);
std::string meta_key_prefix(std::string_view instance_id);
std::string data_key_prefix(std::string_view instance_id);
std::string log_key_prefix(std::string_view instance_id);
+std::string snapshot_key_prefix(std::string_view instance_id);
void partition_version_key(const PartitionVersionKeyInfo& in, std::string* out);
static inline std::string partition_version_key(const PartitionVersionKeyInfo& in) { std::string s; partition_version_key(in, &s); return s; }
@@ -462,7 +480,6 @@ static inline std::string partition_index_key(const PartitionIndexKeyInfo& in) {
void partition_inverted_index_key(const PartitionInvertedIndexKeyInfo& in, std::string* out);
static inline std::string partition_inverted_index_key(const PartitionInvertedIndexKeyInfo& in) { std::string s; partition_inverted_index_key(in, &s); return s; }
-int decode_partition_inverted_index_key(std::string_view* in, int64_t* db_id, int64_t* table_id, int64_t* partition_id);
void tablet_index_key(const TabletIndexKeyInfo& in, std::string* out);
static inline std::string tablet_index_key(const TabletIndexKeyInfo& in) { std::string s; tablet_index_key(in, &s); return s; }
@@ -506,12 +523,16 @@ static inline std::string meta_delete_bitmap_key(const MetaDeleteBitmapInfo& in)
void data_rowset_ref_count_key(const DataRowsetRefCountKeyInfo& in, std::string* out);
static inline std::string data_rowset_ref_count_key(const DataRowsetRefCountKeyInfo& in) { std::string s; data_rowset_ref_count_key(in, &s); return s; }
+void meta_rowset_key(const MetaRowsetKeyInfo& in, std::string* out);
+static inline std::string meta_rowset_key(const MetaRowsetKeyInfo& in) { std::string s; meta_rowset_key(in, &s); return s; }
+
void snapshot_full_key(const SnapshotFullKeyInfo& in, std::string* out);
static inline std::string snapshot_full_key(const SnapshotFullKeyInfo& in) { std::string s; snapshot_full_key(in, &s); return s; }
void snapshot_reference_key(const SnapshotReferenceKeyInfo& in, std::string* out);
static inline std::string snapshot_reference_key(const SnapshotReferenceKeyInfo& in) { std::string s; snapshot_reference_key(in, &s); return s; }
std::string snapshot_reference_key_prefix(std::string_view instance_id, Versionstamp timestamp);
+std::string snapshot_reference_key_prefix(std::string_view instance_id);
void log_key(const LogKeyInfo& in, std::string* out);
static inline std::string log_key(const LogKeyInfo& in) { std::string s; log_key(in, &s); return s; }
@@ -526,14 +547,95 @@ static inline std::string log_key(const LogKeyInfo& in) { std::string s; log_key
*
* @param in input byte stream, successfully decoded part will be consumed
* @param out the vector of each <field decoded, field type and its position> in the input stream
+ * @param timestamp the timestamp of a versioned key
* @return 0 for successful decoding of the entire input, otherwise error.
*/
int decode_key(std::string_view* in,
- std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>>* out);
+ std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>>* out,
+ Versionstamp* timestamp = nullptr);
/**
* Return the list of single version meta key prefixs.
*/
std::vector<std::string> get_single_version_meta_key_prefixs();
+namespace versioned {
+
+// Decode table version key
+// Return true if decode successfully, otherwise false
+bool decode_table_version_key(std::string_view* in, int64_t* table_id, Versionstamp* timestamp);
+
+// Decode partition inverted index key
+// Return true if decode successfully, otherwise false
+bool decode_partition_inverted_index_key(std::string_view* in, int64_t* db_id, int64_t* table_id,
+ int64_t* partition_id);
+
+// Decode meta partition key
+// Return true if decode successfully, otherwise false
+bool decode_meta_partition_key(std::string_view* in, int64_t* partition_id,
+ Versionstamp* timestamp);
+
+// Decode meta index key
+// Return true if decode successfully, otherwise false
+bool decode_meta_index_key(std::string_view* in, int64_t* index_id, Versionstamp* timestamp);
+
+// Decode meta schema key
+// Return true if decode successfully, otherwise false
+bool decode_meta_schema_key(std::string_view* in, int64_t* index_id, int64_t* schema_version);
+
+// Decode meta tablet key
+// Return true if decode successfully, otherwise false
+bool decode_meta_tablet_key(std::string_view* in, int64_t* tablet_id, Versionstamp* timestamp);
+
+// Decode tablet inverted index key
+// Return true if decode successfully, otherwise false
+bool decode_tablet_inverted_index_key(std::string_view* in, int64_t* db_id, int64_t* table_id,
+ int64_t* index_id, int64_t* partition_id, int64_t* tablet_id);
+
+// Decode snapshot reference key
+// Return true if decode successfully, otherwise false
+bool decode_snapshot_ref_key(std::string_view* in, std::string* instance_id,
+ Versionstamp* timestamp, std::string* ref_instance_id);
+
+// Decode data rowset ref count key
+// Return true if decode successfully, otherwise false
+bool decode_data_rowset_ref_count_key(std::string_view* in, int64_t* tablet_id,
+ std::string* rowset_id);
+} // namespace versioned
+
+// Decode stats tablet key
+// Return true if decode successfully, otherwise false
+bool decode_stats_tablet_key(std::string_view* in, int64_t* table_id, int64_t* index_id,
+ int64_t* partition_id, int64_t* tablet_id);
+
+// Decode table version key
+// Return true if decode successfully, otherwise false
+bool decode_table_version_key(std::string_view* in, int64_t* db_id, int64_t* tbl_id);
+
+// Decode tablet schema key
+// Return true if decode successfully, otherwise false
+bool decode_tablet_schema_key(std::string_view* in, int64_t* index_id, int64_t* schema_version);
+
+// Decode partition version key
+// Return true if decode successfully, otherwise false
+bool decode_partition_version_key(std::string_view* in, int64_t* db_id, int64_t* tbl_id,
+ int64_t* partition_id);
+
+// Decode meta tablet key
+// Return true if decode successfully, otherwise false
+bool decode_meta_tablet_key(std::string_view* in, int64_t* table_id, int64_t* index_id,
+ int64_t* partition_id, int64_t* tablet_id);
+
+// Decode meta rowset key
+// Return true if decode successfully, otherwise false
+bool decode_meta_rowset_key(std::string_view* in, int64_t* tablet_id, int64_t* version);
+
+// Decode meta tablet idx key
+// Return true if decode successfully, otherwise false
+bool decode_meta_tablet_idx_key(std::string_view* in, int64_t* tablet_id);
+
+// Decode instance key
+// Return true if decode successfully, otherwise false
+bool decode_instance_key(std::string_view* in, std::string* instance_id);
+
} // namespace doris::cloud
diff --git a/cloud/src/meta-store/mem_txn_kv.cpp b/cloud/src/meta-store/mem_txn_kv.cpp
index dde93b21770..81755043ea1 100644
--- a/cloud/src/meta-store/mem_txn_kv.cpp
+++ b/cloud/src/meta-store/mem_txn_kv.cpp
@@ -207,6 +207,7 @@ TxnErrorCode MemTxnKv::update(const std::set<std::string>& read_set,
++committed_version_;
int16_t seq = 0;
+ std::set<std::string> modified_keys; // Track which keys were modified
for (const auto& vec : op_list) {
const auto& [op_type, k, v] = vec;
LogItem log_item {op_type, committed_version_, k, v};
@@ -214,18 +215,21 @@ TxnErrorCode MemTxnKv::update(const std::set<std::string>& read_set,
switch (op_type) {
case memkv::ModifyOpType::PUT: {
mem_kv_[k].push_front(Version {committed_version_, v});
+ modified_keys.insert(k);
break;
}
case memkv::ModifyOpType::ATOMIC_SET_VER_KEY: {
std::string ver_key(k);
gen_version_timestamp(committed_version_, seq, &ver_key);
mem_kv_[ver_key].push_front(Version {committed_version_, v});
+ modified_keys.insert(ver_key);
break;
}
case memkv::ModifyOpType::ATOMIC_SET_VER_VAL: {
std::string ver_val(v);
gen_version_timestamp(committed_version_, seq, &ver_val);
mem_kv_[k].push_front(Version {committed_version_, ver_val});
+ modified_keys.insert(k);
break;
}
case memkv::ModifyOpType::ATOMIC_ADD: {
@@ -239,10 +243,12 @@ TxnErrorCode MemTxnKv::update(const std::set<std::string>& read_set,
int64_t res = *(int64_t*)org_val.data() + *(int64_t*)v.data();
std::memcpy(org_val.data(), &res, 8);
mem_kv_[k].push_front(Version {committed_version_, org_val});
+ modified_keys.insert(k);
break;
}
case memkv::ModifyOpType::REMOVE: {
mem_kv_[k].push_front(Version {committed_version_, std::nullopt});
+ modified_keys.insert(k);
break;
}
case memkv::ModifyOpType::REMOVE_RANGE: {
@@ -250,6 +256,7 @@ TxnErrorCode MemTxnKv::update(const std::set<std::string>& read_set,
auto end_iter = mem_kv_.lower_bound(v);
while (begin_iter != end_iter) {
mem_kv_[begin_iter->first].push_front(Version {committed_version_, std::nullopt});
+ modified_keys.insert(begin_iter->first);
begin_iter++;
}
break;
@@ -259,6 +266,11 @@ TxnErrorCode MemTxnKv::update(const std::set<std::string>& read_set,
}
}
+ // Trigger watches for all modified keys
+ for (const auto& key : modified_keys) {
+ trigger_watches(key);
+ }
+
*committed_version = committed_version_;
return TxnErrorCode::TXN_OK;
}
@@ -316,6 +328,51 @@ std::unique_ptr<FullRangeGetIterator> MemTxnKv::full_range_get(std::string begin
std::move(opts));
}
+void MemTxnKv::register_watch(const std::string& key, std::shared_ptr<WatchInfo> watch_info) {
+ std::lock_guard<std::mutex> l(lock_);
+ watches_[key].push_back(std::move(watch_info));
+}
+
+void MemTxnKv::trigger_watches(const std::string& key) {
+ // Must be called with lock_ held
+ auto it = watches_.find(key);
+ if (it == watches_.end()) {
+ return;
+ }
+
+ // Get the current version for this key
+ int64_t current_version = -1;
+ auto kv_it = mem_kv_.find(key);
+ if (kv_it != mem_kv_.end() && !kv_it->second.empty()) {
+ current_version = kv_it->second.front().commit_version;
+ }
+
+ // Trigger and remove watches where the version has changed
+ std::vector<std::shared_ptr<WatchInfo>> to_trigger;
+ auto& watch_list = it->second;
+ for (auto iter = watch_list.begin(); iter != watch_list.end();) {
+ auto& watch = *iter;
+ // Trigger if the current version is greater than the watch version
+ // This means the key has been modified since the watch was set
+ if (current_version > watch->watch_version) {
+ to_trigger.push_back(watch);
+ iter = watch_list.erase(iter);
+ } else {
+ ++iter;
+ }
+ }
+
+ if (watch_list.empty()) {
+ watches_.erase(it);
+ }
+
+ for (auto& watch : to_trigger) {
+ std::lock_guard<std::mutex> watch_lock(watch->mutex);
+ watch->triggered = true;
+ watch->cv.notify_all();
+ }
+}
+
} // namespace doris::cloud
namespace doris::cloud::memkv {
@@ -619,6 +676,7 @@ void Transaction::remove(std::string_view begin, std::string_view end) {
std::string begin_k(begin.data(), begin.size());
std::string end_k(end.data(), end.size());
if (begin_k >= end_k) {
+ LOG(WARNING) << "invalid remove range: [" << hex(begin_k) << ", " << hex(end_k) << ")";
aborted_ = true;
} else {
// ATTN: we do not support read your writes about delete range.
@@ -639,10 +697,12 @@ void Transaction::remove(std::string_view begin, std::string_view end) {
TxnErrorCode Transaction::commit() {
std::lock_guard<std::mutex> l(lock_);
if (aborted_) {
+ LOG(WARNING) << "transaction aborted, cannot commit";
return TxnErrorCode::TXN_UNIDENTIFIED_ERROR;
}
auto code = kv_->update(read_set_, op_list_, read_version_, &committed_version_);
if (code != TxnErrorCode::TXN_OK) {
+ LOG(WARNING) << "transaction commit failed, code=" << static_cast<int>(code);
return code;
}
commited_ = true;
@@ -676,6 +736,44 @@ TxnErrorCode Transaction::get_committed_version(int64_t* version) {
return TxnErrorCode::TXN_OK;
}
+TxnErrorCode Transaction::watch_key(std::string_view key) {
+ std::string k(key.data(), key.size());
+
+ // Commit the transaction
+ auto commit_code = commit();
+ if (commit_code != TxnErrorCode::TXN_OK) {
+ return commit_code;
+ }
+
+ int64_t watch_version = read_version_;
+ auto watch_info = std::make_shared<MemTxnKv::WatchInfo>();
+ watch_info->watch_version = watch_version;
+
+ // Register the watch and check if the key has already changed
+ // This is done atomically to avoid race condition
+ {
+ std::lock_guard<std::mutex> l(kv_->lock_);
+
+ // Check if the key has been modified after our watch version
+ auto kv_it = kv_->mem_kv_.find(k);
+ if (kv_it != kv_->mem_kv_.end() && !kv_it->second.empty()) {
+ const auto& latest_version = kv_it->second.front();
+ if (latest_version.commit_version > watch_version) {
+ // Key has already changed, return immediately without blocking
+ return TxnErrorCode::TXN_OK;
+ }
+ }
+
+ // Register the watch only if the key hasn't changed yet
+ kv_->watches_[k].push_back(watch_info);
+ }
+
+ // Wait for the watch to be triggered
+ std::unique_lock<std::mutex> watch_lock(watch_info->mutex);
+ watch_info->cv.wait(watch_lock, [&watch_info] { return watch_info->triggered; });
+
+ return TxnErrorCode::TXN_OK;
+}
TxnErrorCode Transaction::abort() {
return TxnErrorCode::TXN_OK;
}
diff --git a/cloud/src/meta-store/mem_txn_kv.h b/cloud/src/meta-store/mem_txn_kv.h
index f6fa9735634..d7edd1bd5af 100644
--- a/cloud/src/meta-store/mem_txn_kv.h
+++ b/cloud/src/meta-store/mem_txn_kv.h
@@ -17,6 +17,7 @@
#pragma once
+#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <list>
@@ -77,6 +78,15 @@ public:
int64_t put_count_ {};
int64_t del_count_ {};
+ struct WatchInfo {
+ std::mutex mutex;
+ std::condition_variable cv;
+ bool triggered {false};
+ int64_t watch_version {-1};
+ };
+
+ void register_watch(const std::string& key, std::shared_ptr<WatchInfo> watch_info);
+
private:
using OpTuple = std::tuple<memkv::ModifyOpType, std::string, std::string>;
TxnErrorCode update(const std::set<std::string>& read_set, const std::vector<OpTuple>& op_list,
@@ -110,9 +120,12 @@ private:
std::map<std::string, std::list<Version>> mem_kv_;
std::unordered_map<std::string, std::list<LogItem>> log_kv_;
+ std::unordered_map<std::string, std::vector<std::shared_ptr<WatchInfo>>> watches_;
mutable std::mutex lock_;
int64_t committed_version_ = 0;
int64_t read_version_ = 0;
+
+ void trigger_watches(const std::string& key);
};
namespace memkv {
@@ -217,6 +230,8 @@ public:
*/
TxnErrorCode commit() override;
+ TxnErrorCode watch_key(std::string_view key) override;
+
TxnErrorCode get_read_version(int64_t* version) override;
TxnErrorCode get_committed_version(int64_t* version) override;
diff --git a/cloud/src/meta-store/meta_reader.cpp b/cloud/src/meta-store/meta_reader.cpp
index e51fb9fba4c..6a62caa19cf 100644
--- a/cloud/src/meta-store/meta_reader.cpp
+++ b/cloud/src/meta-store/meta_reader.cpp
@@ -17,6 +17,7 @@
#include "meta-store/meta_reader.h"
+#include <gen_cpp/cloud.pb.h>
#include <gen_cpp/olap_file.pb.h>
#include <limits>
@@ -310,6 +311,74 @@ TxnErrorCode MetaReader::get_tablet_compact_stats(
return TxnErrorCode::TXN_OK;
}
+TxnErrorCode MetaReader::get_tablet_load_stats(
+ const std::vector<int64_t>& tablet_ids,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats,
+ std::unordered_map<int64_t, Versionstamp>* versionstamps, bool snapshot) {
+ std::unique_ptr<Transaction> txn;
+ TxnErrorCode err = txn_kv_->create_txn(&txn);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+ return get_tablet_load_stats(txn.get(), tablet_ids, tablet_stats, versionstamps, snapshot);
+}
+
+TxnErrorCode MetaReader::get_tablet_load_stats(
+ Transaction* txn, const std::vector<int64_t>& tablet_ids,
+ std::unordered_map<int64_t, TabletStatsPB>* tablet_stats,
+ std::unordered_map<int64_t, Versionstamp>* versionstamps, bool snapshot) {
+ if (tablet_ids.empty()) {
+ return TxnErrorCode::TXN_OK;
+ }
+
+ std::vector<std::string> tablet_load_stats_keys;
+ for (size_t i = 0; i < tablet_ids.size(); ++i) {
+ int64_t tablet_id = tablet_ids[i];
+ std::string tablet_load_stats_key =
+ versioned::tablet_load_stats_key({instance_id_, tablet_id});
+ tablet_load_stats_keys.push_back(std::move(tablet_load_stats_key));
+ }
+
+ std::vector<std::optional<std::pair<std::string, Versionstamp>>> versioned_values;
+ TxnErrorCode err = versioned_batch_get(txn, tablet_load_stats_keys, snapshot_version_,
+ &versioned_values, snapshot);
+ if (err != TxnErrorCode::TXN_OK) {
+ return err;
+ }
+
+ for (size_t i = 0; i < versioned_values.size(); ++i) {
+ const auto& kv = versioned_values[i];
+ if (!kv.has_value()) {
+ continue; // Key not found, skip
+ }
+
+ const std::string& value = kv->first;
+ Versionstamp versionstamp = kv->second;
+ int64_t tablet_id = tablet_ids[i];
+
+ min_read_versionstamp_ = std::min(min_read_versionstamp_, versionstamp);
+
+ if (versionstamps) {
+ versionstamps->emplace(tablet_id, versionstamp);
+ }
+
+ if (tablet_stats) {
+ TabletStatsPB tablet_stat;
+ if (!tablet_stat.ParseFromString(value)) {
+ LOG_ERROR("Failed to parse TabletStatsPB")
+ .tag("instance_id", instance_id_)
+ .tag("tablet_id", tablet_id)
+ .tag("key", hex(tablet_load_stats_keys[i]))
... 16888 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org