This is an automated email from the ASF dual-hosted git repository.
yujun777 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new a0662fea1d0 [feat](stream) Collect changelog load rows in both storage
modes (#69896)
a0662fea1d0 is described below
commit a0662fea1d048695b751edc9b69933a12cd68eaf
Author: yujun <[email protected]>
AuthorDate: Mon Nov 23 19:05:17 2026 +0800
[feat](stream) Collect changelog load rows in both storage modes (#69896)
### Background
Changelog indexes retain physical change records for table streams.
Their row-count estimates come from periodic tablet statistics,
independently of base-table load statistics. Updates and deletes can
produce changelog records whose counts differ from the base-table load
rows.
### What problem does this PR solve?
Issue Number: None
Related PR: #69850 (persists consumption baselines with offsets and
estimates stream ranges)
PR Type: Enhancement
Problem Summary:
Changelog row counts can remain stale or unknown between tablet reports,
and cloud commit responses previously carried no partition/index-level
changelog delta. Successful visible commits now supplement these
estimates in both storage modes, while valid periodic reports calibrate
retained stock. Most of the diff tests publication, retries, incomplete
reports and recovery; no new configuration is required after upgrading.
### Details
- **Change map:** production code +317/-41, tests +1143/-1, and
generated test output +148/-0; no documentation or generated protocol
source. Production changes have three parts: final published rowset
counting and partition replica normalization in SN; optional MS response
aggregation and version-based deduplication in cloud; valid periodic
stock publication, locking and restored-replica polling. Tests cover
those paths and physical counts.
- **Before and after:** Counts previously waited for periodic reports.
Commits now add physical changelog rows: the regression's
append/update/delete sequence reports 3, 5 and 6. Zero deltas preserve
unknown counts; positive partial estimates do not imply a complete
report. Periodic reports can lower retained counts after TTL cleanup,
and restored cloud replicas fetch valid statistics before resuming
persisted polling backoff.
- **Configs and defaults:** None. No new runtime log statements are
added.
- **Impact on existing users:** Existing SQL and data visibility are
unchanged. Optional protobuf fields preserve compatibility when either
side lacks the new statistics. Counts remain estimates: periodic reports
and deltas can overlap or lag, and failed publication can miss an
immediate delta until the next report.
---
.../storage/task/engine_publish_version_task.cpp | 21 ++
.../engine_storage_migration_task_test.cpp | 134 +++++++-
cloud/src/meta-service/meta_service.cpp | 31 ++
cloud/src/meta-service/meta_service_txn.cpp | 53 +++-
cloud/test/meta_service_versioned_read_test.cpp | 14 +-
cloud/test/txn_lazy_commit_test.cpp | 230 ++++++++++++++
.../apache/doris/catalog/CloudTabletStatMgr.java | 75 ++++-
.../org/apache/doris/catalog/LocalReplica.java | 12 -
.../apache/doris/catalog/MaterializedIndex.java | 71 +++++
.../java/org/apache/doris/catalog/Replica.java | 29 +-
.../org/apache/doris/catalog/TabletStatMgr.java | 68 ++--
.../transaction/CloudGlobalTransactionMgr.java | 37 +++
.../doris/statistics/analysis/AnalysisManager.java | 86 +++--
.../doris/catalog/MaterializedIndexTest.java | 81 +++++
.../apache/doris/catalog/TabletStatMgrTest.java | 350 +++++++++++++++++++++
.../transaction/CloudGlobalTransactionMgrTest.java | 76 +++++
.../statistics/analysis/AnalysisManagerTest.java | 142 +++++++++
gensrc/proto/cloud.proto | 17 +
.../test_changelog_immediate_row_count.out | 104 ++++++
...st_cloud_changelog_subtransaction_row_count.out | 44 +++
.../test_changelog_immediate_row_count.groovy | 130 ++++++++
...cloud_changelog_subtransaction_row_count.groovy | 76 +++++
22 files changed, 1796 insertions(+), 85 deletions(-)
diff --git a/be/src/storage/task/engine_publish_version_task.cpp
b/be/src/storage/task/engine_publish_version_task.cpp
index 1cea9da30af..f0ad457661d 100644
--- a/be/src/storage/task/engine_publish_version_task.cpp
+++ b/be/src/storage/task/engine_publish_version_task.cpp
@@ -132,6 +132,11 @@ Status EnginePublishVersionTask::execute() {
std::unique_ptr<ThreadPoolToken> token =
_engine.tablet_publish_txn_thread_pool()->new_token(
ThreadPool::ExecutionMode::CONCURRENT);
std::unordered_map<int64_t, int64_t> tablet_id_to_num_delta_rows;
+ // The changelog rowsets the transaction wrote, their rows reported once
they are published.
+ // They are retained until this execute attempt finishes; each retry
creates a new collection.
+ // The frontend discards a report containing an error tablet (for base
delta rows as well).
+ // A later periodic tablet report refreshes the row count of tablets
published in a failed attempt.
+ std::vector<RowsetSharedPtr> attached_changelog_rowsets;
#ifndef NDEBUG
if (UNLIKELY(_publish_version_req.partition_version_infos.empty())) {
@@ -248,6 +253,18 @@ Status EnginePublishVersionTask::execute() {
tablet_id_to_num_delta_rows.insert(
{rowset_meta_ptr->tablet_id(),
rowset_meta_ptr->num_rows()});
}
+ // A load which writes a changelog keeps its changelog rowset on
the base tablet's
+ // transaction info instead of committing a changelog tablet of
its own, so its rows are
+ // reported separately below, once the publish tasks have
finished: a merge-on-write
+ // publication can still append changelog segments to that rowset.
The frontend cannot
+ // derive them from the rows it loaded into the base tablets -- an
update writes change
+ // rows without adding a base row, and a delete adds none to the
base but at least one
+ // to the changelog -- and it keeps the count to estimate how many
rows a read of the
+ // changelog returns.
+ const ChangelogTxnInfo& attach_changelog =
txn_info_it->second->attach_changelog;
+ if (attach_changelog.rowset != nullptr) {
+ attached_changelog_rowsets.push_back(attach_changelog.rowset);
+ }
auto tablet_publish_txn_ptr =
std::make_shared<TabletPublishTxnTask>(
_engine, this, tablet, rowset,
txn_info_it->second->attach_changelog,
@@ -317,6 +334,10 @@ Status EnginePublishVersionTask::execute() {
}
}
}
+ for (const RowsetSharedPtr& changelog_rowset : attached_changelog_rowsets)
{
+ const RowsetMetaSharedPtr& rowset_meta =
changelog_rowset->rowset_meta();
+ tablet_id_to_num_delta_rows.insert({rowset_meta->tablet_id(),
rowset_meta->num_rows()});
+ }
_calculate_tbl_num_delta_rows(tablet_id_to_num_delta_rows);
if (!res.is<PUBLISH_VERSION_NOT_CONTINUOUS>()) {
diff --git
a/be/test/storage/schema_change/engine_storage_migration_task_test.cpp
b/be/test/storage/schema_change/engine_storage_migration_task_test.cpp
index e35f8fb6818..2508acd82f1 100644
--- a/be/test/storage/schema_change/engine_storage_migration_task_test.cpp
+++ b/be/test/storage/schema_change/engine_storage_migration_task_test.cpp
@@ -37,7 +37,9 @@
#include "common/config.h"
#include "common/object_pool.h"
+#include "core/block/block.h"
#include "core/data_type/define_primitive_type.h"
+#include "core/field.h"
#include "gtest/gtest_pred_impl.h"
#include "io/fs/local_file_system.h"
#include "load/delta_writer/delta_writer.h"
@@ -45,10 +47,12 @@
#include "runtime/descriptor_helper.h"
#include "runtime/descriptors.h"
#include "runtime/exec_env.h"
+#include "storage/changelog.h"
#include "storage/data_dir.h"
#include "storage/olap_common.h"
#include "storage/olap_define.h"
#include "storage/options.h"
+#include "storage/rowset/rowset_writer_context.h"
#include "storage/rowset_builder.h"
#include "storage/storage_engine.h"
#include "storage/tablet/tablet.h"
@@ -57,6 +61,8 @@
#include "storage/task/engine_publish_version_task.h"
#include "storage/txn/txn_manager.h"
#include "testutil/creators.h"
+#include "util/defer_op.h"
+#include "util/threadpool.h"
namespace doris {
class OlapMeta;
@@ -192,7 +198,8 @@ protected:
void create_changelog_group_load_context(int64_t base_tablet_id, int64_t
changelog_tablet_id,
int64_t transaction_id,
- ChangelogGroupLoadContext*
context) {
+ ChangelogGroupLoadContext*
context,
+ bool need_historical_value =
false) {
RuntimeProfile create_tablet_profile("CreateChangelogTablets");
context->base_request = testutil::create_tablet_request(
base_tablet_id, base_tablet_id + 1000, base_tablet_id + 2000,
1,
@@ -200,6 +207,17 @@ protected:
{{"k1", TPrimitiveType::INT, true}, {"v1",
TPrimitiveType::INT, false}});
context->base_request.__set_enable_unique_key_merge_on_write(true);
testutil::enable_changelog(&context->base_request);
+
context->base_request.binlog_config.__set_need_historical_value(need_historical_value);
+ if (need_historical_value) {
+
context->base_request.tablet_schema.columns[1].__set_aggregation_type(
+ TAggregationType::REPLACE);
+ auto delete_sign =
testutil::create_tablet_column({std::string(DELETE_SIGN),
+
TPrimitiveType::TINYINT, false, true,
+
TAggregationType::REPLACE});
+ delete_sign.__set_visible(false);
+ delete_sign.__set_default_value("0");
+
context->base_request.tablet_schema.columns.push_back(std::move(delete_sign));
+ }
Status status = engine_ref->create_tablet(context->base_request,
&create_tablet_profile);
ASSERT_TRUE(status.ok()) << status;
@@ -212,6 +230,15 @@ protected:
context->changelog_request.tablet_schema =
testutil::create_changelog_tablet_schema(
context->base_request.tablet_schema,
context->base_request.tablet_schema.schema_hash + 1);
+ if (need_historical_value) {
+
context->changelog_request.tablet_schema.columns[1].__set_is_allow_null(true);
+ auto before_column = testutil::create_tablet_column(
+ {changelog::build_before_column_name("v1"),
TPrimitiveType::INT, false, true,
+ TAggregationType::NONE, true});
+ context->changelog_request.tablet_schema.columns.insert(
+ context->changelog_request.tablet_schema.columns.begin() +
2,
+ std::move(before_column));
+ }
context->changelog_request.__set_base_tablet_id(base_tablet_id);
context->changelog_request.__set_tablet_role(TTabletRole::TABLET_ROLE_CHANGELOG);
status = engine_ref->create_tablet(context->changelog_request,
&create_tablet_profile);
@@ -226,6 +253,12 @@ protected:
const int64_t changelog_index_id = base_tablet_id + 4000;
TDescriptorTable descriptor_table = testutil::create_descriptor_table(
{{TYPE_INT, "k1", false}, {TYPE_INT, "v1", false}});
+ if (need_historical_value) {
+ descriptor_table = testutil::create_descriptor_table(
+ {{TYPE_INT, "k1", false},
+ {TYPE_INT, "v1", false},
+ {TYPE_TINYINT, std::string(DELETE_SIGN), false}});
+ }
context->schema_param = testutil::create_table_schema_param(
descriptor_table, index_id,
context->base_request.tablet_schema.schema_hash,
context->base_request.tablet_schema.columns,
changelog_index_id,
@@ -316,8 +349,107 @@ protected:
context.base_request.replica_id, false);
ASSERT_TRUE(status.ok()) << status;
}
+
+ static void build_group_upsert(const ChangelogGroupLoadContext& context,
int32_t key,
+ int32_t value, RowsetSharedPtr*
changelog_rowset) {
+ RuntimeProfile profile("PublishChangelogRowCount");
+ GroupRowsetBuilder builder(*engine_ref, context.group_request,
context.data_request,
+ context.changelog_request_for_write,
&profile);
+ ASSERT_TRUE(builder.init().ok());
+ auto& changelog_context = const_cast<RowsetWriterContext&>(
+ builder.changelog_builder()->rowset_writer()->context());
+ changelog_context.allocated_lsn_map =
+ std::make_shared<segment_v2::SegmentAllocatedLsnMap>();
+ changelog_context.insert_segment_allocated_lsns(
+ 0, std::make_shared<std::vector<int64_t>>(1,
context.data_request.txn_id));
+
+ Block block =
context.base_tablet->tablet_schema()->create_storage_block();
+ {
+ auto columns_guard = block.mutate_columns_scoped();
+ auto& columns = columns_guard.mutable_columns();
+
columns[0]->insert(Field::create_field<PrimitiveType::TYPE_INT>(key));
+
columns[1]->insert(Field::create_field<PrimitiveType::TYPE_INT>(value));
+
columns[2]->insert(Field::create_field<PrimitiveType::TYPE_TINYINT>(0));
+ }
+ Status status = builder.rowset_writer()->flush_single_block(&block);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_TRUE(builder.build_rowset().ok());
+ ASSERT_TRUE(builder.submit_calc_delete_bitmap_task().ok());
+ ASSERT_TRUE(builder.wait_calc_delete_bitmap().ok());
+ ASSERT_TRUE(builder.commit_txn().ok());
+ *changelog_rowset = builder.changelog_builder()->rowset();
+ }
};
+TEST_F(TestEngineStorageMigrationTask,
changelog_publish_reports_final_mow_rows) {
+ // This fixture opens local stores without initializing the file cache.
+ const bool saved_enable_file_cache = config::enable_file_cache;
+ config::enable_file_cache = false;
+ Defer restore_file_cache {[&] { config::enable_file_cache =
saved_enable_file_cache; }};
+ ASSERT_TRUE(ThreadPoolBuilder("PublishChangelogRowCount")
+ .set_min_threads(1)
+ .set_max_threads(1)
+ .build(&engine_ref->_tablet_publish_txn_thread_pool)
+ .ok());
+ ChangelogGroupLoadContext first;
+ create_changelog_group_load_context(13005, 13006, 23005, &first, true);
+ ChangelogGroupLoadContext second = first;
+ for (auto* request :
+ {&second.data_request, &second.changelog_request_for_write,
&second.group_request}) {
+ request->txn_id = 23006;
+ request->load_id.set_hi(23006);
+ request->load_id.set_lo(23006);
+ }
+ // Both writes flush against the initial empty version. The second publish
must rewrite
+ // its changelog with the first transaction's historical value, appending
another segment.
+ RowsetSharedPtr first_changelog;
+ RowsetSharedPtr second_changelog;
+ ASSERT_NO_FATAL_FAILURE(build_group_upsert(first, 1, 10,
&first_changelog));
+ ASSERT_NO_FATAL_FAILURE(build_group_upsert(second, 1, 20,
&second_changelog));
+ ASSERT_EQ(second_changelog->num_rows(), 1);
+ const auto initial_segments = second_changelog->num_segments();
+
+ auto publish = [&](int64_t txn_id, int64_t version,
+ std::map<TTableId, std::map<TTabletId, int64_t>>*
delta_rows) {
+ TPublishVersionRequest request;
+ request.__set_transaction_id(txn_id);
+ request.__set_base_tablet_ids({first.base_tablet->tablet_id()});
+ TPartitionVersionInfo partition;
+ partition.__set_partition_id(first.data_request.partition_id);
+ partition.__set_version(version);
+ partition.__set_commit_tso(version * 100);
+ request.__set_partition_version_infos({partition});
+ std::set<TTabletId> errors;
+ std::map<TTabletId, TVersion> successes;
+ std::vector<DiscontinuousVersionTablet> discontinuous;
+ EnginePublishVersionTask task(*engine_ref, request, &errors,
&successes, &discontinuous,
+ delta_rows);
+ Status status = task.execute();
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_TRUE(errors.empty());
+ };
+ std::map<TTableId, std::map<TTabletId, int64_t>> delta_rows;
+ ASSERT_NO_FATAL_FAILURE(publish(first.data_request.txn_id, 2,
&delta_rows));
+ EXPECT_EQ(delta_rows.at(first.base_tablet->get_table_id())
+ .at(first.changelog_tablet->tablet_id()),
+ first_changelog->num_rows());
+ delta_rows.clear();
+ ASSERT_NO_FATAL_FAILURE(publish(second.data_request.txn_id, 3,
&delta_rows));
+ ASSERT_GT(second_changelog->num_segments(), initial_segments);
+ ASSERT_GT(second_changelog->num_rows(), 1);
+ const auto& tablet_rows = delta_rows.at(first.base_tablet->get_table_id());
+ ASSERT_EQ(tablet_rows.size(), 2);
+ EXPECT_EQ(tablet_rows.at(first.base_tablet->tablet_id()), 1);
+ EXPECT_EQ(tablet_rows.at(first.changelog_tablet->tablet_id()),
second_changelog->num_rows());
+
+ // A retried publish has no committed rowsets left to report, so it must
not re-add the delta.
+ delta_rows.clear();
+ ASSERT_NO_FATAL_FAILURE(publish(second.data_request.txn_id, 3,
&delta_rows));
+ EXPECT_TRUE(delta_rows.empty());
+ drop_changelog_group(first);
+ engine_ref->_tablet_publish_txn_thread_pool.reset();
+}
+
// The two-way migration scenario intentionally keeps setup, publish, and both
migrations together.
// NOLINTNEXTLINE(readability-function-size,
readability-function-cognitive-complexity)
TEST_F(TestEngineStorageMigrationTask, write_and_migration) {
diff --git a/cloud/src/meta-service/meta_service.cpp
b/cloud/src/meta-service/meta_service.cpp
index d4649debdd1..21277b2a9da 100644
--- a/cloud/src/meta-service/meta_service.cpp
+++ b/cloud/src/meta-service/meta_service.cpp
@@ -48,6 +48,7 @@
#include <tuple>
#include <type_traits>
#include <unordered_map>
+#include <unordered_set>
#include <utility>
#include "common/bvars.h"
@@ -3598,6 +3599,9 @@ void
MetaServiceImpl::get_tablet_stats(::google::protobuf::RpcController* contro
bool is_versioned_read = is_version_read_enabled(instance_id);
CloneChainReader reader(instance_id, txn_kv_.get(), resource_mgr_.get());
+ const std::unordered_set<int64_t> versioned_row_counts(
+ request->tablet_ids_with_row_count_version().begin(),
+ request->tablet_ids_with_row_count_version().end());
for (auto& i : request->tablet_idx()) {
TabletIndexPB idx(i);
// FIXME(plat1ko): Get all tablet stats in one txn
@@ -3638,6 +3642,33 @@ void
MetaServiceImpl::get_tablet_stats(::google::protobuf::RpcController* contro
return;
}
}
+ if (versioned_row_counts.contains(idx.tablet_id())) {
+ // Read coverage from the same KV transaction as tablet_stats.
+ VersionPB version;
+ if (is_versioned_read) {
+ err = reader.get_partition_version(txn.get(),
idx.partition_id(), &version,
+ nullptr);
+ } else {
+ auto key = partition_version_key(
+ {instance_id, idx.db_id(), idx.table_id(),
idx.partition_id()});
+ std::string value;
+ err = txn->get(key, &value);
+ if (err == TxnErrorCode::TXN_OK &&
!version.ParseFromString(value)) {
+ code = MetaServiceCode::PROTOBUF_PARSE_ERR;
+ msg = fmt::format("malformed partition version,
tablet_id={}", idx.tablet_id());
+ return;
+ }
+ }
+ if (err != TxnErrorCode::TXN_OK && err !=
TxnErrorCode::TXN_KEY_NOT_FOUND) {
+ code = cast_as<ErrCategory::READ>(err);
+ msg = fmt::format("failed to get row-count version, err={},
tablet_id={}", err,
+ idx.tablet_id());
+ return;
+ }
+ // A new partition starts at version 1. Do not count pending lazy
versions here.
+
tablet_stats->set_row_count_partition_version(version.has_version() ?
version.version()
+
: 1);
+ }
#ifdef NDEBUG
// Force data size >= 0 to reduce the losses caused by bugs
if (tablet_stats->data_size() < 0) tablet_stats->set_data_size(0);
diff --git a/cloud/src/meta-service/meta_service_txn.cpp
b/cloud/src/meta-service/meta_service_txn.cpp
index d983dde49fe..ed6bd4fcd0e 100644
--- a/cloud/src/meta-service/meta_service_txn.cpp
+++ b/cloud/src/meta-service/meta_service_txn.cpp
@@ -441,6 +441,38 @@ static void calc_table_stats(std::unordered_map<int64_t,
TabletIndexPB>& tablet_
}
}
+// Use the transaction's final rowset counters, not the tablet's retained-row
statistics. A
+// changelog tablet is logical in cloud mode, so its rows must not be divided
by replicas.
+static void fill_changelog_stats(const std::unordered_map<int64_t,
TabletIndexPB>& tablet_indexes,
+ const std::unordered_map<int64_t,
TabletStats>& tablet_stats,
+ const std::set<int64_t>& changelog_tablet_ids,
+ CommitTxnResponse* response) {
+ // Most loads have no changelog; avoid building a partition map on that
path.
+ if (changelog_tablet_ids.empty()) {
+ return;
+ }
+ std::unordered_map<int64_t, int64_t> partition_versions;
+ for (int i = 0; i < response->partition_ids_size(); ++i) {
+ partition_versions.emplace(response->partition_ids(i),
response->versions(i));
+ }
+ std::map<std::tuple<int64_t, int64_t, int64_t>, ChangelogStatsPB>
changelog_stats;
+ for (int64_t tablet_id : changelog_tablet_ids) {
+ const auto& tablet_index = tablet_indexes.at(tablet_id);
+ auto& stats = changelog_stats[{tablet_index.table_id(),
tablet_index.partition_id(),
+ tablet_index.index_id()}];
+ stats.set_table_id(tablet_index.table_id());
+ stats.set_partition_id(tablet_index.partition_id());
+ stats.set_index_id(tablet_index.index_id());
+ stats.set_version(partition_versions.at(tablet_index.partition_id()));
+ stats.set_updated_row_count(stats.updated_row_count() +
+ tablet_stats.at(tablet_id).num_rows);
+ stats.add_tablet_ids(tablet_id);
+ }
+ for (auto& [_, stats] : changelog_stats) {
+ response->add_changelog_stats()->Swap(&stats);
+ }
+}
+
//TODO: we need move begin/commit etc txn to TxnManager
void MetaServiceImpl::begin_txn(::google::protobuf::RpcController* controller,
const BeginTxnRequest* request,
BeginTxnResponse* response,
@@ -2154,6 +2186,7 @@ void MetaServiceImpl::commit_txn_immediately(
// <tablet_id, version> -> rowset meta
std::vector<std::pair<std::tuple<int64_t, int64_t>, const
RowsetMetaCloudPB&>> rowsets;
std::unordered_map<int64_t, TabletStats> tablet_stats; // tablet_id ->
stats
+ std::set<int64_t> changelog_tablet_ids;
rowsets.reserve(tmp_rowsets_meta.size());
int64_t rowsets_visible_ts_ms =
@@ -2189,6 +2222,9 @@ void MetaServiceImpl::commit_txn_immediately(
auto& stats = tablet_stats[tablet_id];
stats.data_size += i.total_disk_size();
stats.num_rows += i.num_rows();
+ if (i.is_changelog()) {
+ changelog_tablet_ids.insert(i.tablet_id());
+ }
++stats.num_rowsets;
stats.num_segs += i.num_segments();
stats.index_size += i.index_disk_size();
@@ -2529,6 +2565,7 @@ void MetaServiceImpl::commit_txn_immediately(
}
}
response->mutable_txn_info()->CopyFrom(txn_info);
+ fill_changelog_stats(tablet_ids, tablet_stats, changelog_tablet_ids,
response);
TEST_SYNC_POINT_CALLBACK("commit_txn_immediately::finish", &code);
break;
} while (true);
@@ -3132,11 +3169,15 @@ void MetaServiceImpl::commit_txn_eventually(
}
std::unordered_map<int64_t, TabletStats> tablet_stats; // tablet_id ->
stats
+ std::set<int64_t> changelog_tablet_ids;
for (auto& [_, i] : tmp_rowsets_meta) {
// Accumulate affected rows
auto& stats = tablet_stats[i.tablet_id()];
stats.data_size += i.total_disk_size();
stats.num_rows += i.num_rows();
+ if (i.is_changelog()) {
+ changelog_tablet_ids.insert(i.tablet_id());
+ }
++stats.num_rowsets;
stats.num_segs += i.num_segments();
stats.index_size += i.index_disk_size();
@@ -3164,6 +3205,11 @@ void MetaServiceImpl::commit_txn_eventually(
// txn set visible for fe callback
txn_info.set_status(TxnStatusPB::TXN_STATUS_VISIBLE);
response->mutable_txn_info()->CopyFrom(txn_info);
+ // A failed lazy task leaves a COMMITTED transaction even though the
historical FE
+ // callback below receives VISIBLE. Do not expose additive stats
before publication.
+ if (!response->is_lazy_commit_incomplete()) {
+ fill_changelog_stats(tablet_ids, tablet_stats,
changelog_tablet_ids, response);
+ }
TEST_SYNC_POINT_CALLBACK("commit_txn_eventually::finish", &code,
&txn_id);
break;
} while (true);
@@ -3418,7 +3464,8 @@ void MetaServiceImpl::commit_txn_with_sub_txn(const
CommitTxnRequest* request,
// <tablet_id, version> -> rowset meta
std::vector<std::pair<std::tuple<int64_t, int64_t>,
RowsetMetaCloudPB>> rowsets;
- std::unordered_map<int64_t, TabletStats> tablet_stats; // tablet_id
-> stats
+ std::unordered_map<int64_t, TabletStats> tablet_stats; // tablet_id ->
stats
+ std::set<int64_t> changelog_tablet_ids;
rowsets.reserve(sub_txn_to_tmp_rowsets_meta.size() * 10); // rough
estimate
for (const auto& sub_txn_info : sub_txn_infos) {
auto sub_txn_id = sub_txn_info.sub_txn_id();
@@ -3461,6 +3508,9 @@ void MetaServiceImpl::commit_txn_with_sub_txn(const
CommitTxnRequest* request,
auto& stats = tablet_stats[tablet_id];
stats.data_size += i.total_disk_size();
stats.num_rows += i.num_rows();
+ if (i.is_changelog()) {
+ changelog_tablet_ids.insert(i.tablet_id());
+ }
++stats.num_rowsets;
stats.num_segs += i.num_segments();
stats.index_size += i.index_disk_size();
@@ -3787,6 +3837,7 @@ void MetaServiceImpl::commit_txn_with_sub_txn(const
CommitTxnRequest* request,
}
response->mutable_txn_info()->CopyFrom(txn_info);
+ fill_changelog_stats(tablet_ids, tablet_stats, changelog_tablet_ids,
response);
TEST_SYNC_POINT_CALLBACK("commit_txn_with_sub_txn::finish", &code);
break;
} while (true);
diff --git a/cloud/test/meta_service_versioned_read_test.cpp
b/cloud/test/meta_service_versioned_read_test.cpp
index 3fc8f833a91..9a0f01f8a15 100644
--- a/cloud/test/meta_service_versioned_read_test.cpp
+++ b/cloud/test/meta_service_versioned_read_test.cpp
@@ -889,6 +889,7 @@ TEST(MetaServiceVersionedReadTest, GetTabletStats) {
// The tablet idx should be set.
auto tablet_stats = res.tablet_stats(0);
+ EXPECT_FALSE(tablet_stats.has_row_count_partition_version());
EXPECT_EQ(tablet_stats.idx().tablet_id(), tablet_id);
EXPECT_EQ(tablet_stats.idx().index_id(), index_id);
EXPECT_EQ(tablet_stats.idx().partition_id(), partition_id);
@@ -917,9 +918,20 @@ TEST(MetaServiceVersionedReadTest, GetTabletStats) {
{
GetTabletStatsResponse res;
- get_tablet_stats(meta_service.get(), table_id, index_id, partition_id,
tablet_id, res);
+ GetTabletStatsRequest req;
+ req.set_cloud_unique_id(fmt::format("1:{}:1", instance_id));
+ auto* idx = req.add_tablet_idx();
+ idx->set_db_id(10000);
+ idx->set_tablet_id(tablet_id);
+ idx->set_table_id(table_id);
+ idx->set_index_id(index_id);
+ idx->set_partition_id(partition_id);
+ req.add_tablet_ids_with_row_count_version(tablet_id);
+ brpc::Controller cntl;
+ meta_service->get_tablet_stats(&cntl, &req, &res, nullptr);
ASSERT_EQ(res.status().code(), MetaServiceCode::OK);
ASSERT_EQ(res.tablet_stats_size(), 1);
+ EXPECT_EQ(res.tablet_stats(0).row_count_partition_version(), 8);
EXPECT_EQ(res.tablet_stats(0).data_size(), 77000);
EXPECT_EQ(res.tablet_stats(0).num_rows(), 700);
EXPECT_EQ(res.tablet_stats(0).num_rowsets(), 8);
diff --git a/cloud/test/txn_lazy_commit_test.cpp
b/cloud/test/txn_lazy_commit_test.cpp
index e17056b61bc..3e2495839e0 100644
--- a/cloud/test/txn_lazy_commit_test.cpp
+++ b/cloud/test/txn_lazy_commit_test.cpp
@@ -437,6 +437,236 @@ static void get_table_version(MetaServiceProxy*
meta_service, int64_t db_id, int
version = resp.version();
}
+// Exercise the RPC boundary with final temporary metadata: MoW may append
rows after
+// commit_rowset, and a lazy commit must not expose additive counters before
visibility.
+class ChangelogCommitStatsTest : public testing::Test {
+protected:
+ void SetUp() override {
+ _meta_service = get_meta_service(get_mem_txn_kv(), true);
+ BeginTxnRequest request;
+ request.set_cloud_unique_id("test_cloud_unique_id");
+ auto* info = request.mutable_txn_info();
+ info->set_db_id(DB_ID);
+ info->set_label("changelog_stats");
+ info->add_table_ids(TABLE_ID);
+ info->set_timeout_ms(360000);
+ BeginTxnResponse response;
+ brpc::Controller controller;
+ _meta_service->begin_txn(&controller, &request, &response, nullptr);
+ ASSERT_EQ(response.status().code(), MetaServiceCode::OK);
+ _txn_id = response.txn_id();
+ for (const auto& [tablet_id, index_id, partition_id, rows, changelog]
: TABLETS) {
+ create_tablet_with_db_id(_meta_service.get(), DB_ID, TABLE_ID,
index_id, partition_id,
+ tablet_id);
+ }
+ }
+
+ void write_rowsets(int64_t txn_id) {
+ for (const auto& [tablet_id, index_id, partition_id, rows, changelog]
: TABLETS) {
+ auto rowset = create_rowset(txn_id, tablet_id, index_id,
partition_id);
+ rowset.set_is_changelog(changelog);
+ rowset.set_num_rows(changelog ? 1 : rows);
+ rowset.set_num_segments(1);
+ CreateRowsetResponse response;
+ prepare_rowset(_meta_service.get(), rowset, response);
+ ASSERT_EQ(response.status().code(), MetaServiceCode::OK);
+ commit_rowset(_meta_service.get(), rowset, response);
+ ASSERT_EQ(response.status().code(), MetaServiceCode::OK);
+ if (changelog) {
+ rowset.set_num_rows(rows);
+ CreateRowsetRequest request;
+ request.mutable_rowset_meta()->CopyFrom(rowset);
+ response.Clear();
+ brpc::Controller controller;
+ _meta_service->update_tmp_rowset(&controller, &request,
&response, nullptr);
+ ASSERT_EQ(response.status().code(), MetaServiceCode::OK);
+ }
+ }
+ }
+
+ CommitTxnRequest commit_request(bool lazy) const {
+ CommitTxnRequest request;
+ request.set_cloud_unique_id("test_cloud_unique_id");
+ request.set_db_id(DB_ID);
+ request.set_txn_id(_txn_id);
+ request.set_is_2pc(false);
+ request.set_enable_txn_lazy_commit(lazy);
+ request.add_base_tablet_ids(1001);
+ request.add_base_tablet_ids(1002);
+ return request;
+ }
+
+ void check_stats(const CommitTxnResponse& response, int multiplier,
int64_t version) {
+ ASSERT_EQ(response.status().code(), MetaServiceCode::OK);
+ ASSERT_FALSE(response.is_lazy_commit_incomplete());
+ ASSERT_EQ(response.txn_info().status(),
TxnStatusPB::TXN_STATUS_VISIBLE);
+ ASSERT_EQ(response.table_stats_size(), 1);
+ EXPECT_EQ(response.table_stats(0).updated_row_count(), 28 *
multiplier);
+ ASSERT_EQ(response.changelog_stats_size(), 2);
+ const auto& first = response.changelog_stats(0);
+ EXPECT_EQ(first.table_id(), TABLE_ID);
+ EXPECT_EQ(first.partition_id(), 10);
+ EXPECT_EQ(first.index_id(), 200);
+ EXPECT_EQ(first.updated_row_count(), 20 * multiplier);
+ EXPECT_EQ(first.version(), version);
+ ASSERT_EQ(first.tablet_ids_size(), 2);
+ EXPECT_EQ(first.tablet_ids(0), 2001);
+ EXPECT_EQ(first.tablet_ids(1), 2002);
+ const auto& second = response.changelog_stats(1);
+ EXPECT_EQ(second.table_id(), TABLE_ID);
+ EXPECT_EQ(second.partition_id(), 20);
+ EXPECT_EQ(second.index_id(), 200);
+ EXPECT_EQ(second.updated_row_count(), 3 * multiplier);
+ EXPECT_EQ(second.version(), version);
+ ASSERT_EQ(second.tablet_ids_size(), 1);
+ EXPECT_EQ(second.tablet_ids(0), 2003);
+ }
+
+ CommitTxnResponse commit(const CommitTxnRequest& request) {
+ CommitTxnResponse response;
+ brpc::Controller controller;
+ _meta_service->commit_txn(&controller, &request, &response, nullptr);
+ return response;
+ }
+
+ static constexpr int64_t DB_ID = 300;
+ static constexpr int64_t TABLE_ID = 400;
+ // tablet, index, partition, final physical rows, changelog
+ static constexpr std::tuple<int64_t, int64_t, int64_t, int64_t, bool>
TABLETS[] = {
+ {1001, 100, 10, 11, false}, {1002, 100, 20, 17, false}, {2001,
200, 10, 13, true},
+ {2002, 200, 10, 7, true}, {2003, 200, 20, 3, true}, {3001,
300, 10, 99, false}};
+ int64_t _txn_id;
+ std::unique_ptr<MetaServiceProxy> _meta_service;
+};
+
+TEST_F(ChangelogCommitStatsTest, ImmediateFinalRowsAndRetry) {
+ ASSERT_NO_FATAL_FAILURE(write_rowsets(_txn_id));
+ auto request = commit_request(false);
+ ASSERT_NO_FATAL_FAILURE(check_stats(commit(request), 1, 2));
+ auto retry = commit(request);
+ EXPECT_EQ(retry.status().code(), MetaServiceCode::OK);
+ EXPECT_EQ(retry.changelog_stats_size(), 0);
+}
+
+TEST_F(ChangelogCommitStatsTest, TabletStatsReportPartitionVersion) {
+ GetTabletStatsRequest request;
+ request.set_cloud_unique_id("test_cloud_unique_id");
+ auto* tablet = request.add_tablet_idx();
+ tablet->set_db_id(DB_ID);
+ tablet->set_table_id(TABLE_ID);
+ tablet->set_partition_id(10);
+ tablet->set_index_id(200);
+ tablet->set_tablet_id(2001);
+ request.add_tablet_ids_with_row_count_version(2001);
+
+ auto check_stats = [&](int64_t rows, int64_t version) {
+ GetTabletStatsResponse response;
+ brpc::Controller controller;
+ _meta_service->get_tablet_stats(&controller, &request, &response,
nullptr);
+ ASSERT_EQ(response.status().code(), MetaServiceCode::OK);
+ ASSERT_EQ(response.tablet_stats_size(), 1);
+ EXPECT_EQ(response.tablet_stats(0).num_rows(), rows);
+ EXPECT_EQ(response.tablet_stats(0).row_count_partition_version(),
version);
+ };
+ ASSERT_NO_FATAL_FAILURE(check_stats(0, 1));
+ ASSERT_NO_FATAL_FAILURE(write_rowsets(_txn_id));
+ ASSERT_EQ(commit(commit_request(false)).status().code(),
MetaServiceCode::OK);
+ ASSERT_NO_FATAL_FAILURE(check_stats(13, 2));
+}
+
+TEST_F(ChangelogCommitStatsTest, FailedImmediateOmitsRowsThenRetrySucceeds) {
+ ASSERT_NO_FATAL_FAILURE(write_rowsets(_txn_id));
+ auto* sp = SyncPoint::get_instance();
+ sp->set_call_back("commit_txn_immediately::before_commit", [&](auto&&
args) {
+ *try_any_cast<TxnErrorCode*>(args[0]) = TxnErrorCode::TXN_CONFLICT;
+ *try_any_cast<MetaServiceCode*>(args[1]) =
MetaServiceCode::KV_TXN_CONFLICT;
+ *try_any_cast<bool*>(args.back()) = true;
+ });
+ sp->enable_processing();
+ DORIS_CLOUD_DEFER {
+ sp->clear_all_call_backs();
+ sp->disable_processing();
+ };
+ auto request = commit_request(false);
+ auto failed = commit(request);
+ EXPECT_EQ(failed.status().code(), MetaServiceCode::KV_TXN_CONFLICT);
+ EXPECT_EQ(failed.changelog_stats_size(), 0);
+ sp->clear_all_call_backs();
+ sp->disable_processing();
+ ASSERT_NO_FATAL_FAILURE(check_stats(commit(request), 1, 2));
+}
+
+TEST_F(ChangelogCommitStatsTest, LazyFinalRowsAndRetry) {
+ ASSERT_NO_FATAL_FAILURE(write_rowsets(_txn_id));
+ auto* sp = SyncPoint::get_instance();
+ int32_t original_fuzzy_possibility =
config::cloud_txn_lazy_commit_fuzzy_possibility;
+ config::cloud_txn_lazy_commit_fuzzy_possibility = 100;
+ sp->enable_processing();
+ DORIS_CLOUD_DEFER {
+ config::cloud_txn_lazy_commit_fuzzy_possibility =
original_fuzzy_possibility;
+ sp->clear_all_call_backs();
+ sp->disable_processing();
+ };
+ auto request = commit_request(true);
+ auto response = commit(request);
+ ASSERT_TRUE(response.is_lazy_commit());
+ ASSERT_NO_FATAL_FAILURE(check_stats(response, 1, 2));
+ auto retry = commit(request);
+ EXPECT_EQ(retry.status().code(), MetaServiceCode::OK);
+ EXPECT_EQ(retry.changelog_stats_size(), 0);
+}
+
+TEST_F(ChangelogCommitStatsTest, IncompleteLazyOmitsRows) {
+ ASSERT_NO_FATAL_FAILURE(write_rowsets(_txn_id));
+ int32_t original_fuzzy_possibility =
config::cloud_txn_lazy_commit_fuzzy_possibility;
+ config::cloud_txn_lazy_commit_fuzzy_possibility = 100;
+ auto* sp = SyncPoint::get_instance();
+ sp->set_call_back("convert_tmp_rowsets::before_commit", [&](auto&& args) {
+ *try_any_cast<MetaServiceCode*>(args[0]) =
MetaServiceCode::UNDEFINED_ERR;
+ *try_any_cast<bool*>(args.back()) = true;
+ });
+ sp->enable_processing();
+ DORIS_CLOUD_DEFER {
+ config::cloud_txn_lazy_commit_fuzzy_possibility =
original_fuzzy_possibility;
+ sp->clear_all_call_backs();
+ sp->disable_processing();
+ };
+ auto response = commit(commit_request(true));
+ ASSERT_EQ(response.status().code(), MetaServiceCode::OK);
+ ASSERT_TRUE(response.is_lazy_commit());
+ ASSERT_TRUE(response.is_lazy_commit_incomplete());
+ EXPECT_EQ(response.changelog_stats_size(), 0);
+}
+
+TEST_F(ChangelogCommitStatsTest, SubTransactionsAggregateFinalRows) {
+ ASSERT_NO_FATAL_FAILURE(write_rowsets(_txn_id));
+ BeginSubTxnRequest request;
+ request.set_cloud_unique_id("test_cloud_unique_id");
+ request.set_txn_id(_txn_id);
+ request.set_db_id(DB_ID);
+ request.set_sub_txn_num(0);
+ request.set_label("changelog_stats_sub");
+ request.add_table_ids(TABLE_ID);
+ BeginSubTxnResponse response;
+ brpc::Controller controller;
+ _meta_service->begin_sub_txn(&controller, &request, &response, nullptr);
+ ASSERT_EQ(response.status().code(), MetaServiceCode::OK);
+ ASSERT_NO_FATAL_FAILURE(write_rowsets(response.sub_txn_id()));
+ auto commit_req = commit_request(false);
+ commit_req.set_is_txn_load(true);
+ for (int64_t txn_id : {_txn_id, response.sub_txn_id()}) {
+ auto* sub_txn = commit_req.add_sub_txn_infos();
+ sub_txn->set_sub_txn_id(txn_id);
+ sub_txn->set_table_id(TABLE_ID);
+ sub_txn->add_base_tablet_ids(1001);
+ sub_txn->add_base_tablet_ids(1002);
+ }
+ ASSERT_NO_FATAL_FAILURE(check_stats(commit(commit_req), 2, 3));
+ auto retry = commit(commit_req);
+ EXPECT_EQ(retry.status().code(), MetaServiceCode::OK);
+ EXPECT_EQ(retry.changelog_stats_size(), 0);
+}
+
TEST(TxnLazyCommitTest, CreateTabletWithDbIdTest) {
auto txn_kv = get_mem_txn_kv();
auto meta_service = get_meta_service(txn_kv, true);
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/catalog/CloudTabletStatMgr.java
b/fe/fe-core/src/main/java/org/apache/doris/catalog/CloudTabletStatMgr.java
index 9d050892f7e..d4ad4cf965b 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/CloudTabletStatMgr.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/CloudTabletStatMgr.java
@@ -18,6 +18,7 @@
package org.apache.doris.catalog;
import org.apache.doris.catalog.MaterializedIndex.IndexExtState;
+import org.apache.doris.catalog.Replica.RowCountReport;
import org.apache.doris.cloud.catalog.CloudReplica;
import org.apache.doris.cloud.catalog.CloudTablet;
import org.apache.doris.cloud.proto.Cloud.GetTabletStatsRequest;
@@ -42,6 +43,7 @@ import org.apache.doris.thrift.TStatus;
import org.apache.doris.thrift.TStatusCode;
import org.apache.doris.thrift.TSyncCloudTabletStatsRequest;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -61,7 +63,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
-import java.util.function.Function;
+import java.util.function.BiPredicate;
import java.util.stream.Collectors;
/*
@@ -134,7 +136,7 @@ public class CloudTabletStatMgr extends MasterDaemon {
getActiveTabletStats(copiedTablets);
// get stats by interval
- List<Long> dbIds = getAllTabletStats(cloudTablet -> {
+ List<Long> dbIds = getAllTabletStats((materializedIndex, cloudTablet)
-> {
if (copiedTablets.contains(cloudTablet.getId())) {
return false;
}
@@ -143,6 +145,13 @@ public class CloudTabletStatMgr extends MasterDaemon {
return false;
}
CloudReplica cloudReplica = (CloudReplica) replicas.get(0);
+ // Checkpoints retain polling timers but not report validity. A
recovered idle tablet
+ // at the infinite interval must fetch a valid count before
backoff can apply again.
+ RowCountReport report = cloudReplica.getRowCountReport();
+ if (report == null || materializedIndex.isChangelog()
+ && report.version() <
materializedIndex.getRequiredChangelogReportVersion()) {
+ return true;
+ }
int index = cloudReplica.getStatsIntervalIndex();
if (index >= DEFAULT_INTERVAL_LADDER_MS.length) {
LOG.warn("get tablet stats interval index out of range,
tabletId: {}, index: {}",
@@ -159,7 +168,7 @@ public class CloudTabletStatMgr extends MasterDaemon {
updateStatInfo(dbIds);
}
- private List<Long> getAllTabletStats(Function<CloudTablet, Boolean>
filter) {
+ private List<Long> getAllTabletStats(BiPredicate<MaterializedIndex,
CloudTablet> filter) {
long getStatsTabletNum = 0;
long start = System.currentTimeMillis();
List<Future<Void>> futures = new ArrayList<>();
@@ -185,7 +194,7 @@ public class CloudTabletStatMgr extends MasterDaemon {
for (MaterializedIndex index
:
partition.getMaterializedIndices(IndexExtState.VISIBLE, true)) {
for (Tablet tablet : index.getTablets()) {
- if (filter != null &&
!filter.apply((CloudTablet) tablet)) {
+ if (filter != null && !filter.test(index,
(CloudTablet) tablet)) {
continue;
}
getStatsTabletNum++;
@@ -196,6 +205,9 @@ public class CloudTabletStatMgr extends MasterDaemon {
tabletBuilder.setPartitionId(partition.getId());
tabletBuilder.setTabletId(tablet.getId());
builder.addTabletIdx(tabletBuilder);
+ if (index.isChangelog()) {
+
builder.addTabletIdsWithRowCountVersion(tablet.getId());
+ }
if (builder.getTabletIdxCount() >=
Config.get_tablet_stat_batch_size) {
futures.add(submitGetTabletStatsTask(builder.build(), filter == null));
@@ -244,6 +256,9 @@ public class CloudTabletStatMgr extends MasterDaemon {
}
activeTabletNum++;
builder.addTabletIdx(tabletIndexPB);
+ if (tabletMetas.get(i).isChangelog()) {
+
builder.addTabletIdsWithRowCountVersion(tabletIndexPB.getTabletId());
+ }
if (builder.getTabletIdxCount() >=
Config.get_tablet_stat_batch_size) {
futures.add(submitGetTabletStatsTask(builder.build(), true));
builder = GetTabletStatsRequest.newBuilder()
@@ -274,7 +289,8 @@ public class CloudTabletStatMgr extends MasterDaemon {
.build();
}
- private Future<Void> submitGetTabletStatsTask(GetTabletStatsRequest req,
boolean activeUpdate) {
+ @VisibleForTesting
+ Future<Void> submitGetTabletStatsTask(GetTabletStatsRequest req, boolean
activeUpdate) {
return GET_TABLET_STATS_THREAD_POOL.submit(() -> {
GetTabletStatsResponse resp;
try {
@@ -330,7 +346,7 @@ public class CloudTabletStatMgr extends MasterDaemon {
long tableRowCount = 0L;
- if (!table.readLockIfExist()) {
+ if (!table.writeLockIfExist()) {
continue;
}
OlapTable.Statistics tableStats;
@@ -361,6 +377,10 @@ public class CloudTabletStatMgr extends MasterDaemon {
for (MaterializedIndex index
:
partition.getMaterializedIndices(IndexExtState.VISIBLE, true)) {
long indexRowCount = 0L;
+ long indexReportVersion = Long.MAX_VALUE;
+ long requiredReportVersion =
index.getRequiredChangelogReportVersion();
+ boolean indexReported = true;
+ boolean anyTabletReported = false;
List<Tablet> tablets = index.getTablets();
tabletCount += tablets.size();
for (Tablet tablet : tablets) {
@@ -368,6 +388,8 @@ public class CloudTabletStatMgr extends MasterDaemon {
long tabletChangelogSize = 0L;
long tabletRowCount = 0L;
+ long tabletReportVersion = -1;
+ boolean tabletReported = false;
long tabletIndexSize = 0L;
long tabletSegmentSize = 0L;
@@ -385,8 +407,17 @@ public class CloudTabletStatMgr extends MasterDaemon {
tableTotalChangelogSize +=
replica.getDataSize();
}
- if (replica.getRowCount() >
tabletRowCount) {
- tabletRowCount = replica.getRowCount();
+ // Default replica zeroes before the first
successful MS fetch are
+ // unknown. Count a tablet once even when
it has several replicas.
+ RowCountReport report =
replica.getRowCountReport();
+ if (!index.isChangelog()) {
+ tabletRowCount =
Math.max(tabletRowCount, replica.getRowCount());
+ tabletReported |= report != null;
+ } else if (report != null &&
report.version() >= requiredReportVersion
+ && (!tabletReported ||
report.rows() > tabletRowCount)) {
+ tabletRowCount = Math.max(0,
report.rows());
+ tabletReportVersion = report.version();
+ tabletReported = true;
}
if (replica.getLocalInvertedIndexSize() >
tabletIndexSize) {
@@ -410,6 +441,9 @@ public class CloudTabletStatMgr extends MasterDaemon {
}
indexRowCount += tabletRowCount;
+ indexReportVersion =
Math.min(indexReportVersion, tabletReportVersion);
+ indexReported &= tabletReported;
+ anyTabletReported |= tabletReported;
if (!index.isChangelog()) {
tableRowCount += tabletRowCount;
}
@@ -417,8 +451,18 @@ public class CloudTabletStatMgr extends MasterDaemon {
tableTotalLocalIndexSize += tabletIndexSize;
tableTotalLocalSegmentSize +=
tabletSegmentSize;
} // end for tablets
- index.setRowCountReported(true);
- index.setRowCount(indexRowCount);
+ // Also covers a fetch started before the
regression pauses publication.
+ if
(DebugPointUtil.isEnable("FE.TabletStatMgr.updateIndexRowCount.disabled")) {
+ continue;
+ }
+ // A failed/absent MS fetch must not overwrite a
positive immediate
+ // changelog estimate with the replica's initial
zero.
+ if (!index.isChangelog() || anyTabletReported ||
indexReported) {
+ index.setReportedRowCount(indexRowCount,
indexReported,
+ index.isChangelog() &&
!tablets.isEmpty() ? indexReportVersion : -1);
+ } else {
+ index.setRowCountReported(false);
+ }
} // end for indices
if (maxPartitionSize.second <= partitionDataSize) {
maxPartitionSize = Pair.of("" + partition.getId(),
partitionDataSize);
@@ -434,7 +478,7 @@ public class CloudTabletStatMgr extends MasterDaemon {
minTableSize = Pair.of("" + table.getId(),
tableDataSize);
}
- // this is only one thread to update table statistics,
readLock is enough
+ // The write lock serializes retained counts with
successful commit deltas.
tableStats = new OlapTable.Statistics(db.getName(),
table.getName(), tableDataSize,
tableTotalReplicaDataSize, 0L,
tableReplicaCount, tableRowCount, 0L, 0L,
@@ -444,7 +488,7 @@ public class CloudTabletStatMgr extends MasterDaemon {
LOG.debug("finished to set row num for table: {} in
database: {}",
table.getName(), db.getFullName());
} finally {
- table.readUnlock();
+ table.writeUnlock();
}
totalTableSize += tableDataSize;
newCloudTableStatsList.add(tableStats);
@@ -510,7 +554,12 @@ public class CloudTabletStatMgr extends MasterDaemon {
|| replica.getLocalInvertedIndexSize() !=
stat.getIndexSize()
|| replica.getLocalSegmentSize() != stat.getSegmentSize();
replica.setDataSize(stat.getDataSize());
- replica.setRowCount(stat.getNumRows());
+ // Older/partial responses may omit num_rows. Missing means no
row-count
+ // information, so it cannot establish a known zero or erase a
previous count.
+ if (stat.hasNumRows()) {
+ replica.updateRowCountReport(stat.getNumRows(),
+ stat.hasRowCountPartitionVersion() ?
stat.getRowCountPartitionVersion() : -1);
+ }
replica.setLocalInvertedIndexSize(stat.getIndexSize());
replica.setLocalSegmentSize(stat.getSegmentSize());
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/catalog/LocalReplica.java
b/fe/fe-core/src/main/java/org/apache/doris/catalog/LocalReplica.java
index ab30ec2baac..d1d441212a3 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/LocalReplica.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/LocalReplica.java
@@ -107,8 +107,6 @@ public class LocalReplica extends Replica {
private long scaleInDropTime = -1;
- private long lastReportVersion = 0;
-
private TUniqueId cooldownMetaId;
private long cooldownTerm = -1;
@@ -614,14 +612,4 @@ public class LocalReplica extends Replica {
}
return false;
}
-
- @Override
- public void setLastReportVersion(long version) {
- this.lastReportVersion = version;
- }
-
- @Override
- public long getLastReportVersion() {
- return lastReportVersion;
- }
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/catalog/MaterializedIndex.java
b/fe/fe-core/src/main/java/org/apache/doris/catalog/MaterializedIndex.java
index f04ce04bcab..d0d6a63d37d 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/MaterializedIndex.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/MaterializedIndex.java
@@ -19,6 +19,9 @@ package org.apache.doris.catalog;
import org.apache.doris.persist.gson.GsonPostProcessable;
+import com.google.common.collect.Range;
+import com.google.common.collect.RangeSet;
+import com.google.common.collect.TreeRangeSet;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
@@ -32,6 +35,8 @@ import java.util.Map;
* The OlapTraditional table is a materialized table which stored as
rowcolumnar file or columnar file
*/
public class MaterializedIndex extends MetaObject implements
GsonPostProcessable {
+ private static final int MAX_CHANGELOG_ROW_COUNT_RANGES = 1_024;
+
public enum IndexState {
NORMAL,
@Deprecated
@@ -84,6 +89,14 @@ public class MaterializedIndex extends MetaObject implements
GsonPostProcessable
private boolean rowCountReported = false;
+ // Local estimates need no replay. Consecutive partition versions coalesce
into a single range;
+ // a complete periodic report retires the versions it supersedes. Unlike a
last-version check,
+ // this also counts distinct commit responses delivered out of order, e.g.
version 4 before 3.
+ private transient RangeSet<Long> changelogRowCountVersions;
+ private transient long changelogRowCountReportVersion = -1;
+ // A retained count can replace the estimate only when it covers the last
additive update.
+ private transient long lastChangelogDeltaVersion = -1;
+
public MaterializedIndex() {
this.state = IndexState.NORMAL;
this.idToTablets = new HashMap<>();
@@ -139,6 +152,11 @@ public class MaterializedIndex extends MetaObject
implements GsonPostProcessable
// lookup-by-id drops them. Maintains tablets ⊆ idToTablets.
tablets = new ArrayList<>();
idToTablets = new HashMap<>();
+ rowCount = -1;
+ rowCountReported = false;
+ changelogRowCountVersions = null;
+ changelogRowCountReportVersion = -1;
+ lastChangelogDeltaVersion = -1;
}
public void addTablet(Tablet tablet, TabletMeta tabletMeta) {
@@ -203,6 +221,59 @@ public class MaterializedIndex extends MetaObject
implements GsonPostProcessable
this.rowCount = rowCount;
}
+ /** Caller holds the owning table's write lock, as for periodic
statistics. */
+ public void addChangelogRows(long rows) {
+ // Empty writes (including a replica-normalized zero) cannot turn
unknown into known zero.
+ if (rows > 0) {
+ rowCount = Math.max(0, rowCount) + rows;
+ }
+ }
+
+ /** A publish can report multiple tablet deltas for the same partition
version. */
+ public void addChangelogRowsFromPublish(long version, long rows) {
+ if (rows > 0 && version > changelogRowCountReportVersion) {
+ addChangelogRows(rows);
+ lastChangelogDeltaVersion = Math.max(lastChangelogDeltaVersion,
version);
+ }
+ }
+
+ /** Apply a visible cloud commit once, without dividing its logical rowset
count by replicas. */
+ public void addChangelogRows(long version, long rows) {
+ if (version <= changelogRowCountReportVersion) {
+ return;
+ }
+ if (changelogRowCountVersions == null) {
+ changelogRowCountVersions = TreeRangeSet.create();
+ }
+ // At capacity, wait for a complete report to free ranges without
losing deduplication history.
+ if (changelogRowCountVersions.asRanges().size() >=
MAX_CHANGELOG_ROW_COUNT_RANGES
+ || changelogRowCountVersions.contains(version)) {
+ return;
+ }
+ changelogRowCountVersions.add(Range.closedOpen(version, version + 1));
+ addChangelogRowsFromPublish(version, rows);
+ }
+
+ public long getRequiredChangelogReportVersion() {
+ return Math.max(changelogRowCountReportVersion,
lastChangelogDeltaVersion);
+ }
+
+ /** Replace retained stock (which can decrease after TTL), preserving
partial-report semantics. */
+ public void setReportedRowCount(long rows, boolean reported, long version)
{
+ long requiredVersion = getRequiredChangelogReportVersion();
+ if (version < requiredVersion || !reported && requiredVersion >= 0) {
+ return;
+ }
+ rowCount = rows;
+ rowCountReported = reported;
+ if (reported && version > changelogRowCountReportVersion) {
+ changelogRowCountReportVersion = version;
+ if (changelogRowCountVersions != null) {
+ changelogRowCountVersions.remove(Range.lessThan(version + 1));
+ }
+ }
+ }
+
public void setRollupIndexInfo(long rollupIndexId, long
rollupFinishedVersion) {
this.rollupIndexId = rollupIndexId;
this.rollupFinishedVersion = rollupFinishedVersion;
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/Replica.java
b/fe/fe-core/src/main/java/org/apache/doris/catalog/Replica.java
index 19872ed57f2..550093fcc34 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/Replica.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/Replica.java
@@ -96,6 +96,9 @@ public abstract class Replica {
private volatile long dataSize = 0;
@SerializedName(value = "rc", alternate = {"rowCount"})
private volatile long rowCount = 0;
+ // Keep the count and its coverage together. Replica updates from other
paths can change rowCount.
+ @Getter
+ private transient volatile RowCountReport rowCountReport;
@SerializedName(value = "st", alternate = {"state"})
private volatile ReplicaState state;
@@ -246,6 +249,22 @@ public abstract class Replica {
this.rowCount = rowCount;
}
+ public record RowCountReport(long rows, long version) {
+ }
+
+ public boolean isRowCountReported() {
+ return rowCountReport != null;
+ }
+
+ public synchronized void updateRowCountReport(long rows, long version) {
+ if (rowCountReport == null || version >= rowCountReport.version()) {
+ setRowCount(rows);
+ if (rowCountReport == null || rows != rowCountReport.rows() ||
version != rowCountReport.version()) {
+ rowCountReport = new RowCountReport(rows, version);
+ }
+ }
+ }
+
public long getLastFailedVersion() {
return -1;
@@ -619,14 +638,4 @@ public abstract class Replica {
return
Env.getCurrentSystemInfo().checkBackendScheduleAvailable(getBackendIdValue())
&& !isUserDrop();
}
-
- public void setLastReportVersion(long version) {
- if (version > 0) {
- throw new UnsupportedOperationException("setLastReportVersion is
not supported in Replica");
- }
- }
-
- public long getLastReportVersion() {
- return 0;
- }
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/catalog/TabletStatMgr.java
b/fe/fe-core/src/main/java/org/apache/doris/catalog/TabletStatMgr.java
index 2abf377ac20..1bc2cf1527e 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/TabletStatMgr.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/TabletStatMgr.java
@@ -25,6 +25,7 @@ import org.apache.doris.common.MarkedCountDownLatch;
import org.apache.doris.common.Pair;
import org.apache.doris.common.Status;
import org.apache.doris.common.ThreadPoolManager;
+import org.apache.doris.common.util.DebugPointUtil;
import org.apache.doris.common.util.MasterDaemon;
import org.apache.doris.metric.MetricRepo;
import org.apache.doris.system.Backend;
@@ -162,7 +163,7 @@ public class TabletStatMgr extends MasterDaemon {
Long tableChangelogSize = 0L;
Long tableTotalChangelogSize = 0L;
- if (!table.readLockIfExist()) {
+ if (!table.writeLockIfExist()) {
continue;
}
try {
@@ -191,7 +192,10 @@ public class TabletStatMgr extends MasterDaemon {
for (MaterializedIndex index
:
partition.getMaterializedIndices(IndexExtState.VISIBLE, true)) {
long indexRowCount = 0L;
+ long indexReportVersion = Long.MAX_VALUE;
+ long requiredReportVersion =
index.getRequiredChangelogReportVersion();
boolean indexReported = true;
+ boolean anyTabletReported = false;
List<Tablet> tablets = index.getTablets();
tabletCount += tablets.size();
for (Tablet tablet : tablets) {
@@ -200,33 +204,34 @@ public class TabletStatMgr extends MasterDaemon {
long tabletRemoteDataSize = 0L;
long tabletRowCount = Long.MAX_VALUE;
+ long tabletReportVersion = -1;
Long tabletChangelogSize = 0L;
boolean tabletReported = false;
for (Replica replica : tablet.getReplicas()) {
+ Replica.RowCountReport report =
replica.getRowCountReport();
+ long reportVersion = report == null ? 0 :
report.version();
LOG.debug("Table {} replica {} current
version {}, report version {}",
- olapTable.getName(),
replica.getId(),
- replica.getVersion(),
replica.getLastReportVersion());
+ olapTable.getName(),
replica.getId(), replica.getVersion(), reportVersion);
// Replica with less row count is more
accurate than the others
// when replicas' version are identical.
Because less row count
// means this replica does more compaction
than the others.
+ boolean replicaReported = reportVersion ==
-1
+ || reportVersion >
Partition.PARTITION_INIT_VERSION
+ || reportVersion ==
Partition.PARTITION_INIT_VERSION
+ && replica.getVersion() ==
Partition.PARTITION_INIT_VERSION;
+ long replicaRows = index.isChangelog() &&
report != null
+ ? report.rows() :
replica.getRowCount();
+ // An unreported changelog replica still
has the default zero. Choosing it
+ // over a reported replica would erase a
useful positive estimate.
if (replica.checkVersionCatchUp(version,
false)
- && replica.getRowCount() <
tabletRowCount) {
- // 1. If replica version and reported
replica version are all equal to
- // PARTITION_INIT_VERSION, set
tabletReported to true, which indicates this
- // tablet is empty for sure when
previous report.
- // 2. If last report version is larger
than PARTITION_INIT_VERSION, set
- // tabletReported to true as well.
That is, we only guarantee all replicas of
- // the tablet are reported for the
init version.
- // e.g. When replica version is 2, but
last reported version is 1,
- // tabletReported would be false.
- if (replica.getVersion() ==
Partition.PARTITION_INIT_VERSION
- &&
replica.getLastReportVersion() == Partition.PARTITION_INIT_VERSION
- ||
replica.getLastReportVersion() > Partition.PARTITION_INIT_VERSION) {
- tabletReported = true;
- }
- tabletRowCount = replica.getRowCount();
+ && (!index.isChangelog()
+ || replicaReported &&
reportVersion >= requiredReportVersion)
+ && replicaRows >= 0 && replicaRows
< tabletRowCount) {
+ tabletReported = replicaReported;
+ tabletRowCount = replicaRows;
+ tabletReportVersion = reportVersion;
}
if (replica.getDataSize() >
tabletDataSize) {
@@ -268,16 +273,29 @@ public class TabletStatMgr extends MasterDaemon {
tabletRowCount = 0L;
}
indexRowCount += tabletRowCount;
+ indexReportVersion =
Math.min(indexReportVersion, tabletReportVersion);
if (!index.isChangelog()) {
tableRowCount += tabletRowCount;
}
// Only when all tablets of this index are
reported, we set indexReported to true.
indexReported = indexReported &&
tabletReported;
+ anyTabletReported |= tabletReported;
tableChangelogSize += tabletChangelogSize;
} // end for tablets
- index.setRowCountReported(indexReported);
- index.setRowCount(indexRowCount);
+ // Suspend publication rather than only the daemon
entry, so a report
+ // already in flight cannot mask the
immediate-count regression test.
+ if
(DebugPointUtil.isEnable("FE.TabletStatMgr.updateIndexRowCount.disabled")) {
+ continue;
+ }
+ // No report is different from an empty report:
keep immediate changelog
+ // estimates until at least one tablet has
supplied a valid retained count.
+ if (!index.isChangelog() || anyTabletReported ||
indexReported) {
+ index.setReportedRowCount(indexRowCount,
indexReported,
+ index.isChangelog() &&
!tablets.isEmpty() ? indexReportVersion : -1);
+ } else {
+ index.setRowCountReported(false);
+ }
LOG.debug("Table {} index {} all tablets
reported[{}], row count {}",
olapTable.getName(),
olapTable.getIndexNameById(index.getId()),
indexReported, indexRowCount);
@@ -296,7 +314,7 @@ public class TabletStatMgr extends MasterDaemon {
minTableSize = Pair.of("" + table.getId(),
tableDataSize);
}
- // this is only one thread to update table statistics,
readLock is enough
+ // The write lock serializes retained counts with
transaction visibility deltas.
olapTable.setStatistics(new
OlapTable.Statistics(db.getName(), table.getName(),
tableDataSize, tableTotalReplicaDataSize,
tableRemoteDataSize, tableReplicaCount,
tableRowCount, 0L, 0L,
@@ -309,7 +327,7 @@ public class TabletStatMgr extends MasterDaemon {
table.getName(), db.getFullName());
}
} finally {
- table.readUnlock();
+ table.writeUnlock();
}
totalTableSize += tableDataSize;
}
@@ -404,13 +422,11 @@ public class TabletStatMgr extends MasterDaemon {
replica.setLocalSegmentSize(stat.getLocalSegmentSize());
replica.setRemoteInvertedIndexSize(stat.getRemoteIndexSize());
replica.setRemoteSegmentSize(stat.getRemoteSegmentSize());
- replica.setRowCount(stat.getRowCount());
+ replica.updateRowCountReport(stat.getRowCount(),
+ stat.isSetVisibleVersion() ?
stat.getVisibleVersion() : -1);
replica.setTotalVersionCount(stat.getTotalVersionCount());
replica.setVisibleVersionCount(stat.isSetVisibleVersionCount() ?
stat.getVisibleVersionCount()
: stat.getTotalVersionCount());
- // Older version BE doesn't set visible version. Set
it to max for compatibility.
-
replica.setLastReportVersion(stat.isSetVisibleVersion() ?
stat.getVisibleVersion()
- : Long.MAX_VALUE);
}
}
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgr.java
b/fe/fe-core/src/main/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgr.java
index 16fdbdf7809..3397eb36d9d 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgr.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgr.java
@@ -45,6 +45,7 @@ import org.apache.doris.cloud.proto.Cloud.BeginSubTxnRequest;
import org.apache.doris.cloud.proto.Cloud.BeginSubTxnResponse;
import org.apache.doris.cloud.proto.Cloud.BeginTxnRequest;
import org.apache.doris.cloud.proto.Cloud.BeginTxnResponse;
+import org.apache.doris.cloud.proto.Cloud.ChangelogStatsPB;
import org.apache.doris.cloud.proto.Cloud.CheckTxnConflictRequest;
import org.apache.doris.cloud.proto.Cloud.CheckTxnConflictResponse;
import org.apache.doris.cloud.proto.Cloud.CleanTxnLabelRequest;
@@ -563,6 +564,7 @@ public class CloudGlobalTransactionMgr implements
GlobalTransactionMgrIface {
env.getAnalysisManager().updateUpdatedRows(updatedRows, dbId,
reportedPartitions);
// 2. update table and partition version
Map<Long, List<Long>> tablePartitionMap =
updateVersion(commitTxnResponse);
+ updateChangelogRowCounts(commitTxnResponse);
// 3. notify partition first load
env.getAnalysisManager().setNewPartitionLoaded(
tablePartitionMap.keySet().stream().collect(Collectors.toList()));
@@ -605,6 +607,41 @@ public class CloudGlobalTransactionMgr implements
GlobalTransactionMgrIface {
}
}
+ void updateChangelogRowCounts(CommitTxnResponse response) {
+ // Lazy commit may return txn_info while its visibility task has not
finished. Failed or
+ // incomplete responses must not make uncommitted changelog rows
available to estimation.
+ if (response.getStatus().getCode() != MetaServiceCode.OK
+ || response.getTxnInfo().getStatus() !=
TxnStatusPB.TXN_STATUS_VISIBLE
+ || response.getIsLazyCommitIncomplete() ||
response.getChangelogStatsCount() == 0) {
+ return;
+ }
+ Database db =
Env.getCurrentInternalCatalog().getDbNullable(response.getTxnInfo().getDbId());
+ if (db == null) {
+ return;
+ }
+ for (ChangelogStatsPB stats : response.getChangelogStatsList()) {
+ Table table = db.getTableNullable(stats.getTableId());
+ if (!(table instanceof OlapTable)) {
+ continue;
+ }
+ OlapTable olapTable = (OlapTable) table;
+ olapTable.writeLock();
+ try {
+ Partition partition =
olapTable.getPartition(stats.getPartitionId());
+ MaterializedIndex index = partition == null ? null :
partition.getIndex(stats.getIndexId());
+ // Reject the whole aggregate if its tablet list is empty or
any listed tablet
+ // no longer belongs to the current changelog index.
+ if (index == null || !index.isChangelog() ||
stats.getTabletIdsCount() == 0
+ || stats.getTabletIdsList().stream().anyMatch(id ->
index.getTablet(id) == null)) {
+ continue;
+ }
+ index.addChangelogRows(stats.getVersion(),
stats.getUpdatedRowCount());
+ } finally {
+ olapTable.writeUnlock();
+ }
+ }
+ }
+
private Map<Long, List<Long>> updateVersion(CommitTxnResponse
commitTxnResponse) {
if
(DebugPointUtil.isEnable("FE.CloudGlobalTransactionMgr.updateVersion.disabled"))
{
LOG.info("FE.CloudGlobalTransactionMgr.updateVersion.disabled");
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/statistics/analysis/AnalysisManager.java
b/fe/fe-core/src/main/java/org/apache/doris/statistics/analysis/AnalysisManager.java
index 1fe368d480f..b3b4b6deb18 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/statistics/analysis/AnalysisManager.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/statistics/analysis/AnalysisManager.java
@@ -29,6 +29,7 @@ import org.apache.doris.catalog.ScalarType;
import org.apache.doris.catalog.Table;
import org.apache.doris.catalog.TableIf;
import org.apache.doris.catalog.Tablet;
+import org.apache.doris.catalog.TabletMeta;
import org.apache.doris.catalog.View;
import org.apache.doris.catalog.info.PartitionNamesInfo;
import org.apache.doris.catalog.info.TableNameInfo;
@@ -1505,28 +1506,71 @@ public class AnalysisManager implements Writable {
continue;
}
OlapTable olapTable = (OlapTable) table;
- TableStatsMeta statsStatus = findOrCreateTableStats(olapTable);
- short replicaNum =
olapTable.getTableProperty().getReplicaAllocation().getTotalReplicaNum();
- Map<Long, Long> tabletRows = record.getValue();
- if (tabletRows == null || tabletRows.isEmpty()) {
- LOG.info("Tablet row count map is empty");
- continue;
- }
- long rowsForAllReplica = 0;
- for (Entry<Long, Long> entry : tabletRows.entrySet()) {
- rowsForAllReplica += entry.getValue();
- if (LOG.isDebugEnabled()) {
- LOG.debug("Table id {}, tablet id {}, row count {}",
- record.getKey(), entry.getKey(),
entry.getValue());
+ olapTable.writeLock();
+ try {
+ TableStatsMeta statsStatus =
findOrCreateTableStats(olapTable);
+ short replicaNum =
olapTable.getTableProperty().getReplicaAllocation().getTotalReplicaNum();
+ Map<Long, Long> tabletRows = record.getValue();
+ if (tabletRows == null || tabletRows.isEmpty()) {
+ LOG.info("Tablet row count map is empty");
+ continue;
}
- }
- long tableUpdateRows = rowsForAllReplica / replicaNum;
- LOG.info("Update rows for table {} is {}, replicaNum is {}, "
- + "rows for all replica {}, tablets count {}",
- olapTable.getName(), tableUpdateRows, replicaNum,
rowsForAllReplica, tabletRows.size());
- statsStatus.updatedRows.addAndGet(tableUpdateRows);
- if (StatisticsUtil.enablePartitionAnalyze()) {
- updatePartitionRows(olapTable, tabletRows, statsStatus,
replicaNum);
+ long changelogIndexId = olapTable.hasChangelog()
+ ? olapTable.getChangelogIndexMeta().getIndexId() :
-1;
+ long rowsForAllReplica = 0;
+ boolean enablePartitionAnalyze =
StatisticsUtil.enablePartitionAnalyze();
+ Map<Long, Long> baseTabletRows = enablePartitionAnalyze ?
new HashMap<>() : Collections.emptyMap();
+ for (Entry<Long, Long> entry : tabletRows.entrySet()) {
+ if (changelogIndexId > 0) {
+ TabletMeta tabletMeta =
Env.getCurrentEnv().getTabletInvertedIndex()
+ .getTabletMeta(entry.getKey());
+ // A partition can be force-dropped before the
transaction becomes visible.
+ // Its changelog tablets must not be mistaken for
base tablets after removal.
+ if (tabletMeta == null) {
+ continue;
+ }
+ Partition partition =
olapTable.getPartition(tabletMeta.getPartitionId());
+ if (partition == null) {
+ continue;
+ }
+ if (tabletMeta.getIndexId() == changelogIndexId) {
+ short partitionReplicaNum =
olapTable.getPartitionInfo()
+
.getReplicaAllocation(tabletMeta.getPartitionId()).getTotalReplicaNum();
+ MaterializedIndex changelogIndex =
partition.getIndex(changelogIndexId);
+ // Skip a delayed delta if the tablet no
longer belongs to the current index.
+ if (changelogIndex == null ||
changelogIndex.getTablet(entry.getKey()) == null) {
+ continue;
+ }
+ // Update the partition index that stream P/Q
snapshots read. A periodic
+ // tablet report replaces this estimate with
the retained row count, so
+ // TTL does not leave a lifetime accumulator
behind. The transaction
+ // visibility path holds the table write lock,
excluding tablet stats.
+ long deltaRows = entry.getValue() /
partitionReplicaNum;
+
changelogIndex.addChangelogRowsFromPublish(partition.getVisibleVersion(),
deltaRows);
+ continue;
+ }
+ }
+ rowsForAllReplica += entry.getValue();
+ if (enablePartitionAnalyze) {
+ // Partition accounting only matches base tablets.
A changelog ID left in
+ // its pending map would force a scan of every
partition under the table lock.
+ baseTabletRows.put(entry.getKey(),
entry.getValue());
+ }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Table id {}, tablet id {}, row count
{}",
+ record.getKey(), entry.getKey(),
entry.getValue());
+ }
+ }
+ long tableUpdateRows = rowsForAllReplica / replicaNum;
+ LOG.info("Update rows for table {} is {}, replicaNum is
{}, "
+ + "rows for all replica {}, tablets count {}",
+ olapTable.getName(), tableUpdateRows, replicaNum,
rowsForAllReplica, tabletRows.size());
+ statsStatus.updatedRows.addAndGet(tableUpdateRows);
+ if (enablePartitionAnalyze) {
+ updatePartitionRows(olapTable, baseTabletRows,
statsStatus, replicaNum);
+ }
+ } finally {
+ olapTable.writeUnlock();
}
}
return;
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/catalog/MaterializedIndexTest.java
b/fe/fe-core/src/test/java/org/apache/doris/catalog/MaterializedIndexTest.java
index 080673587d0..642ef7d2606 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/catalog/MaterializedIndexTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/catalog/MaterializedIndexTest.java
@@ -79,6 +79,87 @@ public class MaterializedIndexTest {
Assertions.assertEquals(indexId, index.getId());
}
+ @Test
+ public void testChangelogPartialCountsAndVisibleCommitIdempotence() {
+ Assertions.assertEquals(-1, index.getRowCount());
+ index.addChangelogRows(0);
+ Assertions.assertEquals(-1, index.getRowCount());
+ index.addChangelogRows(4, 7);
+ index.addChangelogRows(3, 5);
+ index.addChangelogRows(4, 7);
+ Assertions.assertEquals(12, index.getRowCount());
+ Assertions.assertFalse(index.getRowCountReported());
+ index.setReportedRowCount(2, false, 4);
+ index.addChangelogRows(3, 5);
+ Assertions.assertEquals(12, index.getRowCount());
+ index.setReportedRowCount(0, true, 4);
+ index.addChangelogRows(3, 5);
+ Assertions.assertEquals(0, index.getRowCount());
+ index.addChangelogRows(5, 3);
+ Assertions.assertEquals(3, index.getRowCount());
+
+ // Restore can keep the index ID while replacing its data and
resetting version numbers.
+ index.clearTabletsForRestore();
+ Assertions.assertEquals(-1, index.getRowCount());
+ index.addChangelogRows(2, 4);
+ Assertions.assertEquals(4, index.getRowCount());
+ MaterializedIndex restored =
GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(index), MaterializedIndex.class);
+ Assertions.assertFalse(restored.getRowCountReported());
+ restored.addChangelogRows(3, 2);
+ Assertions.assertEquals(6, restored.getRowCount());
+ }
+
+ @Test
+ public void testStaleReportPreservesVisibleChangelogDelta() {
+ index.setIsChangelog(true);
+ index.setReportedRowCount(0, true, 3);
+ index.addChangelogRows(4, 10);
+ index.setReportedRowCount(0, true, 3);
+ Assertions.assertEquals(10, index.getRowCount());
+ index.setReportedRowCount(0, false, 4);
+ Assertions.assertEquals(10, index.getRowCount());
+
+ index.setReportedRowCount(8, true, 4);
+ index.addChangelogRows(4, 10);
+ index.setReportedRowCount(0, true, 3);
+ Assertions.assertEquals(8, index.getRowCount());
+ }
+
+ @Test
+ public void testChangelogRangeLimitPausesUntilCompleteReport() {
+ int rangeLimit = 1_024;
+ long nextVersion = 2L * rangeLimit + 2;
+ for (long version = 2; version < nextVersion; version += 2) {
+ index.addChangelogRows(version, 1);
+ }
+ Assertions.assertEquals(rangeLimit, index.getRowCount());
+
+ index.addChangelogRows(3, 10);
+ index.addChangelogRows(nextVersion, 10);
+ Assertions.assertEquals(rangeLimit, index.getRowCount());
+
+ index.setReportedRowCount(rangeLimit, false, nextVersion);
+ index.addChangelogRows(nextVersion, 10);
+ Assertions.assertEquals(rangeLimit, index.getRowCount());
+
+ index.setReportedRowCount(rangeLimit, true, nextVersion - 2);
+ index.addChangelogRows(2, 10);
+ index.addChangelogRows(4, 10);
+ Assertions.assertEquals(rangeLimit, index.getRowCount());
+ index.addChangelogRows(nextVersion, 1);
+ Assertions.assertEquals(rangeLimit + 1, index.getRowCount());
+ index.addChangelogRows(nextVersion + 2, 10);
+ Assertions.assertEquals(rangeLimit + 11, index.getRowCount());
+ }
+
+ @Test
+ public void testConsecutiveChangelogVersionsFitInOneRange() {
+ for (long version = 2; version <= 1_026; version++) {
+ index.addChangelogRows(version, 1);
+ }
+ Assertions.assertEquals(1_025, index.getRowCount());
+ }
+
@Test
public void testChangelogFlagGsonUpgradeCompatibility() {
MaterializedIndex changelogIndex = new MaterializedIndex(1L,
IndexState.NORMAL);
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/catalog/TabletStatMgrTest.java
b/fe/fe-core/src/test/java/org/apache/doris/catalog/TabletStatMgrTest.java
new file mode 100644
index 00000000000..08ef13ff110
--- /dev/null
+++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/TabletStatMgrTest.java
@@ -0,0 +1,350 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.catalog;
+
+import org.apache.doris.cloud.catalog.CloudReplica;
+import org.apache.doris.cloud.catalog.CloudTablet;
+import org.apache.doris.cloud.proto.Cloud.GetTabletStatsRequest;
+import org.apache.doris.cloud.proto.Cloud.GetTabletStatsResponse;
+import org.apache.doris.cloud.proto.Cloud.MetaServiceCode;
+import org.apache.doris.cloud.proto.Cloud.MetaServiceResponseStatus;
+import org.apache.doris.cloud.proto.Cloud.TabletIndexPB;
+import org.apache.doris.cloud.proto.Cloud.TabletStatsPB;
+import org.apache.doris.common.Config;
+import org.apache.doris.datasource.InternalCatalog;
+import org.apache.doris.persist.gson.GsonUtils;
+import org.apache.doris.service.FrontendOptions;
+import org.apache.doris.system.SystemInfoService;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+
+public class TabletStatMgrTest {
+ @Test
+ public void
testLocalChangelogReportsPreserveUnknownAndReplaceRetainedCount() throws
Exception {
+ InternalCatalog catalog = new InternalCatalog();
+ MaterializedIndex changelog = createTable(catalog);
+ OlapTable table = (OlapTable)
catalog.getDbNullable(10L).getTableNullable(20L);
+ MaterializedIndex base = table.getPartition(30L).getBaseIndex();
+ LocalReplica baseReplica = localReplica(100L, 10L, true);
+ LocalTablet baseTablet = new LocalTablet(100L);
+ baseTablet.addReplica(baseReplica, true);
+ base.addTablet(baseTablet, null, true);
+ LocalReplica reportedReplica = localReplica(200L, 8L, false);
+ LocalReplica defaultReplica = localReplica(201L, 0L, false);
+ LocalReplica otherTabletReplica = localReplica(300L, 0L, false);
+ LocalTablet first = new LocalTablet(200L);
+ first.addReplica(reportedReplica, true);
+ first.addReplica(defaultReplica, true);
+ LocalTablet second = new LocalTablet(300L);
+ second.addReplica(otherTabletReplica, true);
+ changelog.addTablet(first, null, true);
+ changelog.addTablet(second, null, true);
+ changelog.setRowCount(12L);
+ SystemInfoService systemInfo = Mockito.mock(SystemInfoService.class);
+
Mockito.when(systemInfo.getAllBackendsByAllCluster()).thenReturn(ImmutableMap.of());
+ try (MockedStatic<Env> env = Mockito.mockStatic(Env.class)) {
+ env.when(Env::getCurrentInternalCatalog).thenReturn(catalog);
+ env.when(Env::getCurrentSystemInfo).thenReturn(systemInfo);
+ TabletStatMgr manager = new TabletStatMgr();
+ manager.runAfterCatalogReady();
+ Assertions.assertEquals(12L, changelog.getRowCount());
+ Assertions.assertFalse(changelog.getRowCountReported());
+
+ reportedReplica.updateRowCountReport(8L, 2L);
+ manager.runAfterCatalogReady();
+ Assertions.assertEquals(8L, changelog.getRowCount());
+ Assertions.assertFalse(changelog.getRowCountReported());
+ Assertions.assertEquals(10L, base.getRowCount());
+
+ // Pick one reported replica per tablet, preserving the existing
minimum-row policy.
+ defaultReplica.updateRowCountReport(3L, 2L);
+ otherTabletReplica.updateRowCountReport(4L, 2L);
+ manager.runAfterCatalogReady();
+ Assertions.assertEquals(7L, changelog.getRowCount());
+ Assertions.assertTrue(changelog.getRowCountReported());
+ defaultReplica.setRowCount(0L);
+ manager.runAfterCatalogReady();
+ Assertions.assertEquals(7L, changelog.getRowCount());
+
+ // Replica current versions advance at publish, independently of
the row-count report.
+ table.getPartition(30L).setVisibleVersionAndTime(3L, 200L);
+ reportedReplica.updateVersion(3L);
+ defaultReplica.updateVersion(3L);
+ otherTabletReplica.updateVersion(3L);
+ changelog.addChangelogRowsFromPublish(3L, 10L);
+ manager.runAfterCatalogReady();
+ Assertions.assertEquals(17L, changelog.getRowCount());
+ reportedReplica.updateRowCountReport(8L, 3L);
+ manager.runAfterCatalogReady();
+ Assertions.assertEquals(17L, changelog.getRowCount());
+
+ // A later retained count can decrease after TTL, including a
known empty index.
+ reportedReplica.updateRowCountReport(0L, 3L);
+ defaultReplica.updateRowCountReport(0L, 3L);
+ otherTabletReplica.updateRowCountReport(0L, 3L);
+ manager.runAfterCatalogReady();
+ Assertions.assertEquals(0L, changelog.getRowCount());
+ Assertions.assertTrue(changelog.getRowCountReported());
+ }
+ }
+
+ @Test
+ public void
testCloudChangelogNeedsValidRowsAndAllowsPartialAndEmptyReports() throws
Exception {
+ InternalCatalog catalog = new InternalCatalog();
+ MaterializedIndex changelog = createTable(catalog);
+ CloudReplica firstReplica = cloudReplica(200L);
+ CloudReplica secondReplica = cloudReplica(300L);
+ CloudTablet first = new CloudTablet(200L);
+ first.addReplica(firstReplica, true);
+ CloudTablet second = new CloudTablet(300L);
+ second.addReplica(secondReplica, true);
+ changelog.addTablet(first, null, true);
+ changelog.addTablet(second, null, true);
+ changelog.setRowCount(12L);
+ TabletInvertedIndex invertedIndex =
Mockito.mock(TabletInvertedIndex.class);
+
Mockito.when(invertedIndex.getReplicasByTabletId(200L)).thenReturn(Collections.singletonList(firstReplica));
+
Mockito.when(invertedIndex.getReplicasByTabletId(300L)).thenReturn(Collections.singletonList(secondReplica));
+ Method aggregate =
CloudTabletStatMgr.class.getDeclaredMethod("updateStatInfo", List.class);
+ aggregate.setAccessible(true);
+ Method update =
CloudTabletStatMgr.class.getDeclaredMethod("updateTabletStat",
+ GetTabletStatsResponse.class, boolean.class);
+ update.setAccessible(true);
+ int oldStatsVersion = Config.cloud_get_tablet_stats_version;
+ Config.cloud_get_tablet_stats_version = 1;
+ try (MockedStatic<Env> env = Mockito.mockStatic(Env.class)) {
+ env.when(Env::getCurrentInternalCatalog).thenReturn(catalog);
+ env.when(Env::getCurrentInvertedIndex).thenReturn(invertedIndex);
+ CloudTabletStatMgr manager = new CloudTabletStatMgr();
+ changelog.setRowCount(-1L);
+ aggregate.invoke(manager, Collections.singletonList(10L));
+ Assertions.assertEquals(-1L, changelog.getRowCount());
+ Assertions.assertFalse(changelog.getRowCountReported());
+ changelog.setRowCount(12L);
+ aggregate.invoke(manager, Collections.singletonList(10L));
+ Assertions.assertEquals(12L, changelog.getRowCount());
+ Assertions.assertFalse(changelog.getRowCountReported());
+
+ // An older response without num_rows conveys no row-count
information.
+ update.invoke(manager,
GetTabletStatsResponse.newBuilder().addTabletStats(
+
TabletStatsPB.newBuilder().setIdx(TabletIndexPB.newBuilder().setTabletId(200L))).build(),
false);
+ aggregate.invoke(manager, Collections.singletonList(10L));
+ Assertions.assertFalse(firstReplica.isRowCountReported());
+ Assertions.assertEquals(12L, changelog.getRowCount());
+ Assertions.assertFalse(changelog.getRowCountReported());
+
+ update.invoke(manager, cloudRows(200L, 8L), true);
+ aggregate.invoke(manager, Collections.singletonList(10L));
+ Assertions.assertEquals(8L, changelog.getRowCount());
+ Assertions.assertFalse(changelog.getRowCountReported());
+
+ update.invoke(manager, cloudRows(300L, 4L), false);
+ aggregate.invoke(manager, Collections.singletonList(10L));
+ Assertions.assertEquals(12L, changelog.getRowCount());
+ Assertions.assertTrue(changelog.getRowCountReported());
+
+ changelog.addChangelogRows(4L, 10L);
+ update.invoke(manager, cloudRows(200L, 0L, 3L), false);
+ update.invoke(manager, cloudRows(300L, 0L, 3L), false);
+ aggregate.invoke(manager, Collections.singletonList(10L));
+ Assertions.assertEquals(22L, changelog.getRowCount());
+ update.invoke(manager, cloudRows(200L, 0L, 4L), false);
+ aggregate.invoke(manager, Collections.singletonList(10L));
+ Assertions.assertEquals(22L, changelog.getRowCount());
+ update.invoke(manager, cloudRows(300L, 0L, 4L), false);
+ aggregate.invoke(manager, Collections.singletonList(10L));
+ Assertions.assertEquals(0L, changelog.getRowCount());
+ Assertions.assertTrue(changelog.getRowCountReported());
+ Assertions.assertEquals(0L,
manager.getCloudTableStats().get(0).getRowCount());
+ } finally {
+ Config.cloud_get_tablet_stats_version = oldStatsVersion;
+ }
+ }
+
+ @Test
+ public void testCloudCountsReplicasOnce() throws Exception {
+ InternalCatalog catalog = new InternalCatalog();
+ MaterializedIndex changelog = createTable(catalog);
+ CloudReplica firstReplica = cloudReplica(200L);
+ CloudReplica secondReplica = cloudReplica(201L);
+ firstReplica.updateRowCountReport(8L, 2L);
+ secondReplica.updateRowCountReport(9L, 2L);
+ Tablet tablet = Mockito.mock(Tablet.class);
+ Mockito.when(tablet.getId()).thenReturn(200L);
+
Mockito.when(tablet.getReplicas()).thenReturn(Arrays.asList(firstReplica,
secondReplica));
+ changelog.addTablet(tablet, null, true);
+ Method aggregate =
CloudTabletStatMgr.class.getDeclaredMethod("updateStatInfo", List.class);
+ aggregate.setAccessible(true);
+ try (MockedStatic<Env> env = Mockito.mockStatic(Env.class)) {
+ env.when(Env::getCurrentInternalCatalog).thenReturn(catalog);
+ aggregate.invoke(new CloudTabletStatMgr(),
Collections.singletonList(10L));
+ Assertions.assertEquals(9L, changelog.getRowCount());
+ Assertions.assertTrue(changelog.getRowCountReported());
+ }
+ }
+
+ @Test
+ public void testCloudReplicaRecoveryDoesNotManufactureReportCompleteness()
{
+ CloudReplica replica = cloudReplica(200L);
+ replica.updateRowCountReport(8L, 2L);
+ CloudReplica restored =
GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(replica), CloudReplica.class);
+ Assertions.assertEquals(8L, restored.getRowCount());
+ Assertions.assertFalse(restored.isRowCountReported());
+ }
+
+ @Test
+ public void testCloudModeTwoRevalidatesRestoredRowsBeforePollingBackoff()
throws Exception {
+ InternalCatalog catalog = new InternalCatalog();
+ MaterializedIndex changelog = createTable(catalog);
+ OlapTable table = (OlapTable)
catalog.getDbNullable(10L).getTableNullable(20L);
+ MaterializedIndex base = table.getPartition(30L).getBaseIndex();
+ CloudReplica baseReplica = new CloudReplica(100L, -1L,
Replica.ReplicaState.NORMAL,
+ 2L, 0, 10L, 20L, 30L, 40L, -1L);
+ CloudReplica changelogReplica = cloudReplica(200L);
+ baseReplica.setRowCount(8L);
+ changelogReplica.setRowCount(13L);
+ baseReplica.setStatsIntervalIndex(8); // Stable tablets can persist an
infinite interval.
+ changelogReplica.setStatsIntervalIndex(7); // Also cover an unexpired
finite interval.
+ for (CloudReplica replica : Arrays.asList(baseReplica,
changelogReplica)) {
+ replica.setLastGetTabletStatsTime(System.currentTimeMillis());
+ replica.updateRowCountReport(replica.getRowCount(), 2L);
+ }
+ CloudReplica restoredBase =
GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(baseReplica), CloudReplica.class);
+ CloudReplica restoredChangelog = GsonUtils.GSON.fromJson(
+ GsonUtils.GSON.toJson(changelogReplica), CloudReplica.class);
+ CloudTablet baseTablet = new CloudTablet(100L);
+ baseTablet.addReplica(restoredBase, true);
+ base.addTablet(baseTablet, null, true);
+ CloudTablet changelogTablet = new CloudTablet(200L);
+ changelogTablet.addReplica(restoredChangelog, true);
+ changelog.addTablet(changelogTablet, null, true);
+ TabletInvertedIndex invertedIndex =
Mockito.mock(TabletInvertedIndex.class);
+
Mockito.when(invertedIndex.getReplicas(100L)).thenReturn(Collections.singletonList(restoredBase));
+
Mockito.when(invertedIndex.getReplicas(200L)).thenReturn(Collections.singletonList(restoredChangelog));
+
Mockito.when(invertedIndex.getReplicasByTabletId(100L)).thenReturn(Collections.singletonList(restoredBase));
+
Mockito.when(invertedIndex.getReplicasByTabletId(200L)).thenReturn(Collections.singletonList(restoredChangelog));
+ List<GetTabletStatsRequest> requests = new ArrayList<>();
+ Method update =
CloudTabletStatMgr.class.getDeclaredMethod("updateTabletStat",
+ GetTabletStatsResponse.class, boolean.class);
+ update.setAccessible(true);
+ int oldStatsVersion = Config.cloud_get_tablet_stats_version;
+ Config.cloud_get_tablet_stats_version = 2;
+ try (MockedStatic<Env> env = Mockito.mockStatic(Env.class);
+ MockedStatic<FrontendOptions> frontend =
Mockito.mockStatic(FrontendOptions.class)) {
+ env.when(Env::getCurrentInternalCatalog).thenReturn(catalog);
+ env.when(Env::getCurrentInvertedIndex).thenReturn(invertedIndex);
+
frontend.when(FrontendOptions::getLocalHostAddressCached).thenReturn("127.0.0.1");
+ CloudTabletStatMgr manager = Mockito.spy(new CloudTabletStatMgr());
+ // Replace only transport/executor submission. Exercise the actual
mode-2 selection,
+ // request construction, successful report handling and index
aggregation.
+ Mockito.doAnswer(invocation -> {
+ GetTabletStatsRequest request = invocation.getArgument(0);
+ requests.add(request);
+ if (requests.size() == 2) {
+ update.invoke(manager, GetTabletStatsResponse.newBuilder()
+
.setStatus(MetaServiceResponseStatus.newBuilder().setCode(MetaServiceCode.OK))
+ .addAllTabletStats(cloudRows(100L,
8L).getTabletStatsList())
+ .addAllTabletStats(cloudRows(200L,
13L).getTabletStatsList()).build(), false);
+ } else if (requests.size() == 3) {
+ update.invoke(manager, cloudRows(200L, 18L, 3L), false);
+ }
+ return CompletableFuture.completedFuture(null);
+ }).when(manager).submitGetTabletStatsTask(Mockito.any(),
Mockito.anyBoolean());
+ // A failed first fetch leaves both replicas unknown; the next
cycle must retry them.
+ manager.runAfterCatalogReady();
+ Assertions.assertEquals(1, requests.size());
+ Assertions.assertEquals(2, requests.get(0).getTabletIdxCount());
+ Assertions.assertFalse(restoredBase.isRowCountReported());
+ Assertions.assertFalse(restoredChangelog.isRowCountReported());
+ Assertions.assertFalse(base.getRowCountReported());
+ Assertions.assertFalse(changelog.getRowCountReported());
+ manager.runAfterCatalogReady();
+ Assertions.assertEquals(2, requests.size());
+ Assertions.assertEquals(2, requests.get(1).getTabletIdxCount());
+ Assertions.assertEquals(List.of(200L),
requests.get(1).getTabletIdsWithRowCountVersionList());
+ Assertions.assertTrue(base.getRowCountReported());
+ Assertions.assertTrue(changelog.getRowCountReported());
+ Assertions.assertEquals(8L, table.getRowCountForIndex(40L, true));
+ Assertions.assertEquals(13L,
table.getRowCountForPartitionIndex(30L, 50L, true));
+ // Valid, unchanged replicas resume their persisted backoff
instead of polling every cycle.
+ manager.runAfterCatalogReady();
+ Assertions.assertEquals(2, requests.size());
+
+ changelog.addChangelogRows(3L, 5L);
+ manager.runAfterCatalogReady();
+ Assertions.assertEquals(3, requests.size());
+ Assertions.assertEquals(1, requests.get(2).getTabletIdxCount());
+ Assertions.assertEquals(List.of(200L),
requests.get(2).getTabletIdsWithRowCountVersionList());
+ Assertions.assertEquals(18L, changelog.getRowCount());
+ Assertions.assertTrue(changelog.getRowCountReported());
+ } finally {
+ Config.cloud_get_tablet_stats_version = oldStatsVersion;
+ }
+ }
+
+ private MaterializedIndex createTable(InternalCatalog catalog) {
+ Database db = new Database(10L, "changelog_periodic_stats");
+ catalog.unprotectCreateDb(db);
+ OlapTable table = new OlapTable(20L, "changelog_rows",
Collections.emptyList(), KeysType.DUP_KEYS,
+ Mockito.mock(PartitionInfo.class), null);
+ table.setBaseIndexId(40L);
+ MaterializedIndex base = new MaterializedIndex(40L,
MaterializedIndex.IndexState.NORMAL);
+ MaterializedIndex changelog = new MaterializedIndex(50L,
MaterializedIndex.IndexState.NORMAL);
+ changelog.setIsChangelog(true);
+ Partition partition = new Partition(30L, "p1", base, null);
+ partition.setVisibleVersionAndTime(2L, 100L);
+ partition.createRollupIndex(changelog);
+ table.addPartition(partition);
+ db.registerTable(table);
+ return changelog;
+ }
+
+ private LocalReplica localReplica(long id, long rows, boolean reported) {
+ LocalReplica replica = new LocalReplica(id, id,
Replica.ReplicaState.NORMAL, 2L, 0);
+ if (reported) {
+ replica.updateRowCountReport(rows, 2L);
+ } else {
+ replica.setRowCount(rows);
+ }
+ return replica;
+ }
+
+ private CloudReplica cloudReplica(long id) {
+ return new CloudReplica(id, -1L, Replica.ReplicaState.NORMAL, 2L, 0,
10L, 20L, 30L, 50L, -1L);
+ }
+
+ private GetTabletStatsResponse cloudRows(long tabletId, long rows) {
+ return cloudRows(tabletId, rows, 2L);
+ }
+
+ private GetTabletStatsResponse cloudRows(long tabletId, long rows, long
version) {
+ return
GetTabletStatsResponse.newBuilder().addTabletStats(TabletStatsPB.newBuilder()
+
.setIdx(TabletIndexPB.newBuilder().setTabletId(tabletId)).setNumRows(rows)
+ .setRowCountPartitionVersion(version)).build();
+ }
+}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgrTest.java
b/fe/fe-core/src/test/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgrTest.java
index b42bad02352..5c3b2fc9372 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgrTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgrTest.java
@@ -26,6 +26,7 @@ import org.apache.doris.catalog.Env;
import org.apache.doris.catalog.FakeEditLog;
import org.apache.doris.catalog.FakeEnv;
import org.apache.doris.catalog.KeysType;
+import org.apache.doris.catalog.LocalTablet;
import org.apache.doris.catalog.MaterializedIndex;
import org.apache.doris.catalog.MaterializedIndexMeta;
import org.apache.doris.catalog.OlapTable;
@@ -1035,6 +1036,81 @@ public class CloudGlobalTransactionMgrTest {
}
}
+ @Test
+ public void testChangelogCommitCountsAreSeparateAndIdempotent() throws
Exception {
+ CloudPartition first = addCloudPartition(1000);
+ CloudPartition second = addCloudPartition(2000);
+ MaterializedIndex firstIndex = addChangelogIndex(first, 11, 101);
+ MaterializedIndex secondIndex = addChangelogIndex(second, 12, 102);
+ firstIndex.appendTablets(List.of(new LocalTablet(103)));
+ Cloud.ChangelogStatsPB firstStats = changelogStats(first, firstIndex,
3, 9);
+ CommitTxnResponse response = visibleRetry(List.of(first.getTableId(),
second.getTableId())).toBuilder()
+
.addChangelogStats(firstStats).addChangelogStats(changelogStats(second,
secondIndex, 3, 15)).build();
+ masterTransMgr.afterCommitTxnResp(response, null, List.of());
+ Assertions.assertEquals(9, firstIndex.getRowCount());
+ Assertions.assertEquals(15, secondIndex.getRowCount());
+ Assertions.assertFalse(firstIndex.getRowCountReported());
+ masterTransMgr.afterCommitTxnResp(response, null, List.of());
+ Assertions.assertEquals(9, firstIndex.getRowCount());
+ Assertions.assertEquals(15, secondIndex.getRowCount());
+ ((CloudGlobalTransactionMgr)
masterTransMgr).updateChangelogRowCounts(response.toBuilder()
+ .clearChangelogStats().addChangelogStats(changelogStats(first,
firstIndex, 5, 4)).build());
+ ((CloudGlobalTransactionMgr)
masterTransMgr).updateChangelogRowCounts(response.toBuilder()
+ .clearChangelogStats().addChangelogStats(changelogStats(first,
firstIndex, 4, 2)).build());
+ Assertions.assertEquals(15, firstIndex.getRowCount());
+ firstIndex.setReportedRowCount(1, true, 5);
+ masterTransMgr.afterCommitTxnResp(response, null, List.of());
+ Assertions.assertEquals(1, firstIndex.getRowCount());
+ // The changelog path never creates base-table analysis statistics.
+
Assertions.assertNull(masterEnv.getAnalysisManager().findTableStatsStatus(first.getTableId()));
+ }
+
+ @Test
+ public void testChangelogIgnoresIncompleteAndReplacedData() throws
Exception {
+ CloudPartition partition = addCloudPartition(1000);
+ MaterializedIndex index = addChangelogIndex(partition, 11, 101);
+ CommitTxnResponse response =
visibleRetry(List.of(partition.getTableId())).toBuilder()
+ .addChangelogStats(changelogStats(partition, index, 3,
8)).build();
+ CloudGlobalTransactionMgr manager = (CloudGlobalTransactionMgr)
masterTransMgr;
+
manager.updateChangelogRowCounts(response.toBuilder().setIsLazyCommitIncomplete(true).build());
+
manager.updateChangelogRowCounts(response.toBuilder().setTxnInfo(response.getTxnInfo().toBuilder()
+ .setStatus(Cloud.TxnStatusPB.TXN_STATUS_COMMITTED)).build());
+
manager.updateChangelogRowCounts(response.toBuilder().setStatus(Cloud.MetaServiceResponseStatus.newBuilder()
+ .setCode(MetaServiceCode.KV_TXN_CONFLICT)).build());
+
manager.updateChangelogRowCounts(response.toBuilder().clearChangelogStats()
+ .addChangelogStats(changelogStats(partition, index, 2,
0)).build());
+ Assertions.assertEquals(-1, index.getRowCount());
+ Assertions.assertFalse(index.getRowCountReported());
+ index.clearTabletsForRestore();
+ index.appendTablets(List.of(new LocalTablet(102)));
+ manager.updateChangelogRowCounts(response);
+ Assertions.assertEquals(-1, index.getRowCount());
+ MaterializedIndex replacement = addChangelogIndex(partition, 11, 103);
+ manager.updateChangelogRowCounts(response);
+ Assertions.assertEquals(-1, replacement.getRowCount());
+
getCloudTable(partition).getPartitionInfo().addPartition(partition.getId(),
+ new DataProperty(org.apache.doris.thrift.TStorageMedium.HDD),
+ ReplicaAllocation.DEFAULT_ALLOCATION, false, true);
+
getCloudTable(partition).dropPartitionAndReserveTablet(partition.getName());
+ manager.updateChangelogRowCounts(response);
+ Assertions.assertEquals(-1, replacement.getRowCount());
+ }
+
+ private MaterializedIndex addChangelogIndex(CloudPartition partition, long
indexId, long tabletId) {
+ MaterializedIndex index = new MaterializedIndex(indexId,
MaterializedIndex.IndexState.NORMAL);
+ index.setIsChangelog(true);
+ index.appendTablets(List.of(new LocalTablet(tabletId)));
+ partition.createRollupIndex(index);
+ return index;
+ }
+
+ private Cloud.ChangelogStatsPB changelogStats(CloudPartition partition,
MaterializedIndex index,
+ long version, long rows) {
+ return
Cloud.ChangelogStatsPB.newBuilder().setTableId(partition.getTableId())
+
.setPartitionId(partition.getId()).setIndexId(index.getId()).setVersion(version)
+
.addAllTabletIds(index.getTabletIdsInOrder()).setUpdatedRowCount(rows).build();
+ }
+
@Test
public void testVisibleRetryInvalidatesTableAndPartitionVersions() throws
Exception {
useVersionCaches();
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/statistics/analysis/AnalysisManagerTest.java
b/fe/fe-core/src/test/java/org/apache/doris/statistics/analysis/AnalysisManagerTest.java
index d206daa759d..d0f2f1a312f 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/statistics/analysis/AnalysisManagerTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/statistics/analysis/AnalysisManagerTest.java
@@ -22,12 +22,21 @@ import org.apache.doris.catalog.Column;
import org.apache.doris.catalog.Database;
import org.apache.doris.catalog.DatabaseIf;
import org.apache.doris.catalog.Env;
+import org.apache.doris.catalog.KeysType;
+import org.apache.doris.catalog.LocalTablet;
+import org.apache.doris.catalog.LocalTabletInvertedIndex;
+import org.apache.doris.catalog.MaterializedIndex;
+import org.apache.doris.catalog.MaterializedIndexMeta;
import org.apache.doris.catalog.OlapTable;
import org.apache.doris.catalog.Partition;
+import org.apache.doris.catalog.PartitionInfo;
import org.apache.doris.catalog.PrimitiveType;
+import org.apache.doris.catalog.RecyclePartitionParam;
import org.apache.doris.catalog.ReplicaAllocation;
import org.apache.doris.catalog.TableIf;
import org.apache.doris.catalog.TableProperty;
+import org.apache.doris.catalog.TabletInvertedIndex;
+import org.apache.doris.catalog.TabletMeta;
import org.apache.doris.catalog.info.TableNameInfo;
import org.apache.doris.common.Config;
import org.apache.doris.common.DdlException;
@@ -52,6 +61,7 @@ import
org.apache.doris.statistics.analysis.AnalysisInfo.ScheduleType;
import org.apache.doris.statistics.util.DBObjects;
import org.apache.doris.statistics.util.StatisticsUtil;
import org.apache.doris.thrift.TQueryColumn;
+import org.apache.doris.thrift.TStorageMedium;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -725,6 +735,138 @@ public class AnalysisManagerTest {
return table;
}
+ @Test
+ public void testChangelogRowCountUpdatedByLoadsAndPartitionLifecycle()
throws Exception {
+ AnalysisManager manager = new AnalysisManager();
+ InternalCatalog catalog = new InternalCatalog();
+ Database db = new Database(20001L, "test_changelog_tablet_rows");
+ catalog.unprotectCreateDb(db);
+ PartitionInfo partitionInfo = Mockito.mock(PartitionInfo.class);
+ OlapTable table = Mockito.spy(new OlapTable(30001L, "t_changelog",
ImmutableList.of(),
+ KeysType.DUP_KEYS, partitionInfo, null));
+ table.setBaseIndexId(10001L);
+ Mockito.doReturn(db).when(table).getDatabase();
+ TableProperty tableProperty = Mockito.mock(TableProperty.class);
+ Mockito.doReturn(tableProperty).when(table).getTableProperty();
+ Mockito.when(tableProperty.getReplicaAllocation()).thenReturn(new
ReplicaAllocation((short) 3));
+ db.registerTable(table);
+ long changelogIndexId = 10002L;
+ MaterializedIndexMeta changelogMeta =
Mockito.mock(MaterializedIndexMeta.class);
+ Mockito.when(changelogMeta.getIndexId()).thenReturn(changelogIndexId);
+ Mockito.doReturn(true).when(table).hasChangelog();
+ Mockito.doReturn(changelogMeta).when(table).getChangelogIndexMeta();
+ Mockito.when(partitionInfo.getReplicaAllocation(10L)).thenReturn(new
ReplicaAllocation((short) 1));
+ Mockito.when(partitionInfo.getReplicaAllocation(20L)).thenReturn(new
ReplicaAllocation((short) 3));
+ MaterializedIndex baseOne = Mockito.spy(new MaterializedIndex(
+ table.getBaseIndexId(), MaterializedIndex.IndexState.NORMAL));
+ MaterializedIndex baseThree = Mockito.spy(new MaterializedIndex(
+ table.getBaseIndexId(), MaterializedIndex.IndexState.NORMAL));
+ baseThree.appendTablets(ImmutableList.of(new LocalTablet(1L)));
+ Partition partitionOne = new Partition(10L, "p_one", baseOne, null);
+ Partition partitionThree = new Partition(20L, "p_three", baseThree,
null);
+ partitionOne.updateVisibleVersionAndTime(2L, 100L);
+ partitionThree.updateVisibleVersionAndTime(2L, 200L);
+ MaterializedIndex indexOne = new MaterializedIndex(changelogIndexId,
MaterializedIndex.IndexState.NORMAL);
+ MaterializedIndex indexThree = new MaterializedIndex(changelogIndexId,
MaterializedIndex.IndexState.NORMAL);
+ indexOne.setIsChangelog(true);
+ indexOne.appendTablets(ImmutableList.of(new LocalTablet(2L)));
+ indexThree.setIsChangelog(true);
+ indexThree.appendTablets(ImmutableList.of(new LocalTablet(3L)));
+ indexThree.setRowCount(100);
+ partitionOne.createRollupIndex(indexOne);
+ partitionThree.createRollupIndex(indexThree);
+ table.addPartition(partitionOne);
+ table.addPartition(partitionThree);
+
+ TabletInvertedIndex invertedIndex = new LocalTabletInvertedIndex();
+ invertedIndex.addTablet(1L, new TabletMeta(db.getId(), table.getId(),
20L,
+ table.getBaseIndexId(), 0, TStorageMedium.HDD, false));
+ invertedIndex.addTablet(2L, new TabletMeta(db.getId(), table.getId(),
10L,
+ changelogIndexId, 0, TStorageMedium.HDD, true));
+ invertedIndex.addTablet(3L, new TabletMeta(db.getId(), table.getId(),
20L,
+ changelogIndexId, 0, TStorageMedium.HDD, true));
+ Env env = Mockito.mock(Env.class);
+ Mockito.when(env.getTabletInvertedIndex()).thenReturn(invertedIndex);
+ Map<Long, Map<Long, Long>> tabletRecords =
ImmutableMap.of(table.getId(),
+ ImmutableMap.of(1L, 12L, 2L, 9L, 3L, 18L));
+ try (MockedStatic<Env> envMockedStatic =
Mockito.mockStatic(Env.class)) {
+
envMockedStatic.when(Env::getCurrentInternalCatalog).thenReturn(catalog);
+ envMockedStatic.when(Env::getCurrentEnv).thenReturn(env);
+ try (MockedStatic<StatisticsUtil> suStatic =
Mockito.mockStatic(StatisticsUtil.class)) {
+
suStatic.when(StatisticsUtil::enablePartitionAnalyze).thenReturn(true);
+ manager.replayUpdateRowsRecord(new
UpdateRowsEvent(tabletRecords, db.getId()));
+ }
+ TableStatsMeta record =
manager.findTableStatsStatus(table.getId());
+ Assertions.assertEquals(4, record.updatedRows.get());
+ Assertions.assertEquals(ImmutableMap.of(20L, 4L),
record.partitionUpdateRows);
+ // The loaded base tablet is in the newest partition. Once it is
matched, changelog
+ // IDs must not keep the pending map nonempty and probe the older
partition.
+ Mockito.verify(baseThree).getTablet(1L);
+ Mockito.verify(baseOne,
Mockito.never()).getTablet(Mockito.anyLong());
+ Assertions.assertEquals(ImmutableMap.of(1L, 12L, 2L, 9L, 3L, 18L),
tabletRecords.get(table.getId()));
+ Assertions.assertEquals(9, indexOne.getRowCount());
+ Assertions.assertEquals(106, indexThree.getRowCount());
+ Assertions.assertEquals(9, table.getRowCountForPartitionIndex(10L,
changelogIndexId, false));
+ Assertions.assertEquals(106,
table.getRowCountForPartitionIndex(20L, changelogIndexId, false));
+ Assertions.assertEquals(115,
table.getRowCountForIndex(changelogIndexId, false));
+ Assertions.assertFalse(indexOne.getRowCountReported());
+ Assertions.assertFalse(indexThree.getRowCountReported());
+
+ // No loaded row (or fewer replica rows than the partition
allocation) conveys no
+ // information about the retained stock and must leave an unknown
baseline untouched.
+ indexOne.setRowCount(-1);
+ indexThree.setRowCount(-1);
+ manager.replayUpdateRowsRecord(new
UpdateRowsEvent(ImmutableMap.of(table.getId(),
+ ImmutableMap.of(2L, 0L, 3L, 2L)), db.getId()));
+ Assertions.assertEquals(-1, indexOne.getRowCount());
+ Assertions.assertEquals(-1, indexThree.getRowCount());
+ indexOne.setRowCount(9);
+ indexThree.setRowCount(106);
+
+
+ // A late transaction report can still contain a force-dropped
changelog tablet.
+ invertedIndex.deleteTablet(2L);
+ manager.replayUpdateRowsRecord(new UpdateRowsEvent(tabletRecords,
db.getId()));
+ Assertions.assertEquals(8, record.updatedRows.get());
+ Assertions.assertEquals(9, indexOne.getRowCount());
+ Assertions.assertEquals(112, indexThree.getRowCount());
+
+ // DROP STATS/recreation does not erase the changelog row-count
baseline.
+ manager.removeTableStats(table.getId());
+ manager.replayUpdateTableStatsStatus(new TableStatsMeta(table));
+ record = manager.findTableStatsStatus(table.getId());
+ Assertions.assertEquals(121,
table.getRowCountForIndex(changelogIndexId, false));
+
+ // Periodic tablet statistics replace the estimate after TTL
removes rowsets.
+ indexThree.setRowCount(5);
+ Assertions.assertEquals(5, table.getRowCountForPartitionIndex(20L,
changelogIndexId, false));
+ manager.replayUpdateRowsRecord(new UpdateRowsEvent(tabletRecords,
db.getId()));
+ Assertions.assertEquals(4, record.updatedRows.get());
+ Assertions.assertEquals(11,
table.getRowCountForPartitionIndex(20L, changelogIndexId, false));
+
+ // Tablet identity protects replacements even when partition and
index IDs stay the same.
+ indexThree.clearTabletsForRestore();
+ indexThree.appendTablets(ImmutableList.of(new LocalTablet(4L)));
+ manager.replayUpdateRowsRecord(new
UpdateRowsEvent(ImmutableMap.of(table.getId(),
+ ImmutableMap.of(3L, 18L)), db.getId()));
+ Assertions.assertEquals(-1, indexThree.getRowCount());
+ Assertions.assertEquals(4, record.updatedRows.get());
+
+
+ // A partial TRUNCATE replaces just this partition and its
changelog index. Old
+ // reports must not repopulate it, even while the old tablet
metadata still exists.
+ Partition replacement = new Partition(30L, "p_three", new
MaterializedIndex(
+ table.getBaseIndexId(),
MaterializedIndex.IndexState.NORMAL), null);
+ replacement.createRollupIndex(new
MaterializedIndex(changelogIndexId, MaterializedIndex.IndexState.NORMAL));
+ table.replacePartition(replacement, new RecyclePartitionParam());
+ manager.replayUpdateRowsRecord(new UpdateRowsEvent(tabletRecords,
db.getId()));
+ Assertions.assertEquals(4, record.updatedRows.get());
+ Assertions.assertEquals(0, table.getRowCountForPartitionIndex(30L,
changelogIndexId, false));
+ Assertions.assertEquals(9,
table.getRowCountForIndex(changelogIndexId, false));
+ Assertions.assertEquals(9, indexOne.getRowCount());
+ }
+ }
+
/**
* A load recreates the statistics record of a table whose record was
removed, e.g. by TRUNCATE TABLE, and
* accumulates the loaded rows into it. The record is created on the
transaction visibility of the load,
diff --git a/gensrc/proto/cloud.proto b/gensrc/proto/cloud.proto
index 254aa7a3814..ecba9bb3d64 100644
--- a/gensrc/proto/cloud.proto
+++ b/gensrc/proto/cloud.proto
@@ -1021,6 +1021,8 @@ message TabletStatsPB {
// - Normal case: dynamically filled with ClusterPB.mtime (not persisted)
// - Deleted case: persisted when first detected as deleted, reused
thereafter
optional int64 last_active_cluster_status_mtime_ms = 19;
+ // Partition version from the same metadata snapshot as num_rows. Set on
request.
+ optional int64 row_count_partition_version = 20;
}
message ObjectFilePB {
@@ -1138,6 +1140,18 @@ message TableStatsPB {
optional int64 table_version = 3;
}
+// Physical changelog rows written by this transaction, separate from base
table statistics.
+message ChangelogStatsPB {
+ optional int64 table_id = 1;
+ optional int64 partition_id = 2;
+ optional int64 index_id = 3;
+ optional int64 updated_row_count = 4;
+ // Preserve tablet identity so a late response cannot update replacement
data.
+ repeated int64 tablet_ids = 5;
+ // Final partition version, including all subtransactions in this commit.
+ optional int64 version = 6;
+}
+
message CommitTxnResponse {
optional MetaServiceResponseStatus status = 1;
optional TxnInfoPB txn_info = 2;
@@ -1154,6 +1168,8 @@ message CommitTxnResponse {
optional bool is_lazy_commit_incomplete = 9;
// The current master fence when commit_tso is rejected as stale.
optional int64 tso_fence = 10;
+ // Absent on retries of visible transactions and before lazy visibility
completes.
+ repeated ChangelogStatsPB changelog_stats = 11;
}
message AbortTxnRequest {
@@ -1767,6 +1783,7 @@ message GetTabletStatsRequest {
optional string cloud_unique_id = 1;
repeated TabletIndexPB tablet_idx = 2;
optional string request_ip = 3;
+ repeated int64 tablet_ids_with_row_count_version = 4;
}
message GetTabletStatsResponse {
diff --git
a/regression-test/data/changelog_p0/test_changelog_immediate_row_count.out
b/regression-test/data/changelog_p0/test_changelog_immediate_row_count.out
new file mode 100644
index 00000000000..c38aebedc98
--- /dev/null
+++ b/regression-test/data/changelog_p0/test_changelog_immediate_row_count.out
@@ -0,0 +1,104 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !order_index_rows_after_append --
+base 0
+changelog 3
+total -
+
+-- !physical_rows_after_append --
+3
+
+-- !stream_append --
+1 10 APPEND
+2 20 APPEND
+3 30 APPEND
+
+-- !order_index_rows_after_update --
+base 0
+changelog 5
+total -
+
+-- !physical_rows_after_update --
+5
+
+-- !stream_update --
+1 10 APPEND
+1 10 UPDATE_BEFORE
+1 11 UPDATE_AFTER
+2 20 APPEND
+2 20 UPDATE_BEFORE
+2 21 UPDATE_AFTER
+3 30 APPEND
+
+-- !order_index_rows_after_delete --
+base 0
+changelog 6
+total -
+
+-- !physical_rows_after_delete --
+6
+
+-- !stream_delete --
+1 10 APPEND
+1 10 UPDATE_BEFORE
+1 11 UPDATE_AFTER
+2 20 APPEND
+2 20 UPDATE_BEFORE
+2 21 UPDATE_AFTER
+3 30 APPEND
+3 30 DELETE
+
+-- !base_after_delete --
+1 11
+2 21
+
+-- !order_index_rows_after_drop_stats --
+base 0
+changelog 6
+total -
+
+-- !order_index_rows_after_truncate --
+base 0
+changelog 0
+total -
+
+-- !order_index_rows_after_replacement_load --
+base 0
+changelog 2
+total -
+
+-- !physical_rows_after_replacement_load --
+2
+
+-- !order_index_rows_before_first_consumption --
+base 0
+changelog 3
+total -
+
+-- !empty_after_first_consumption --
+0
+
+-- !order_index_rows_after_first_consumption --
+base 0
+changelog 3
+total -
+
+-- !order_index_rows_between_consumptions --
+base 0
+changelog 4
+total -
+
+-- !rows_after_second_load --
+0 400 APPEND
+
+-- !empty_after_second_consumption --
+0
+
+-- !consumed_rows_between_reports --
+0 400
+3 300
+
+-- !order_index_rows_after_second_consumption --
+base 0
+changelog 4
+total -
+
diff --git
a/regression-test/data/changelog_p0/test_cloud_changelog_subtransaction_row_count.out
b/regression-test/data/changelog_p0/test_cloud_changelog_subtransaction_row_count.out
new file mode 100644
index 00000000000..bb6dc47d59b
--- /dev/null
+++
b/regression-test/data/changelog_p0/test_cloud_changelog_subtransaction_row_count.out
@@ -0,0 +1,44 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !order_index_rows_after_commit --
+base 0
+changelog 4
+total -
+
+-- !physical_rows_after_commit --
+4
+
+-- !rows_after_commit --
+1 10
+2 20
+3 30
+4 40
+
+-- !order_index_rows_after_rollback --
+base 0
+changelog 4
+total -
+
+-- !physical_rows_after_rollback --
+4
+
+-- !rows_after_rollback --
+1 10
+2 20
+3 30
+4 40
+
+-- !order_index_rows_after_next_commit --
+base 0
+changelog 5
+total -
+
+-- !physical_rows_after_next_commit --
+5
+
+-- !rows_after_next_commit --
+1 10
+2 20
+3 30
+4 40
+5 50
+
diff --git
a/regression-test/suites/changelog_p0/test_changelog_immediate_row_count.groovy
b/regression-test/suites/changelog_p0/test_changelog_immediate_row_count.groovy
new file mode 100644
index 00000000000..c283db9b17f
--- /dev/null
+++
b/regression-test/suites/changelog_p0/test_changelog_immediate_row_count.groovy
@@ -0,0 +1,130 @@
+// 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.
+
+suite("test_changelog_immediate_row_count", "nonConcurrent") {
+ // The debug point changes global statistics publication; run on both SN
and cloud.
+ def pauseReports = "FE.TabletStatMgr.updateIndexRowCount.disabled"
+ def recordIndexRows = { tag ->
+ // SHOW DATA reads the index's retained-count estimate directly.
Project by column name
+ // so deployment-dependent byte sizes and replica counts do not enter
the golden file.
+ quickRunTest(tag, "SHOW DATA FROM changelog_immediate_rows", true, {
row, meta ->
+ def columns = (1..meta.getColumnCount()).collectEntries { column ->
+ [(meta.getColumnLabel(column)): row[column - 1]]
+ }
+ def indexName = columns.IndexName
+ def kind = indexName == "changelog_immediate_rows" ? "base" :
+ (indexName == "Total" ? "total" : "changelog")
+ return [kind, kind == "total" ? "-" : columns.RowCount]
+ })
+ }
+
+ GetDebugPoint().enableDebugPointForAllFEs(pauseReports)
+ try {
+ sql "DROP STREAM IF EXISTS changelog_report_gap_stream FORCE"
+ sql "DROP TABLE IF EXISTS changelog_report_gap_sink FORCE"
+ sql "DROP STREAM IF EXISTS changelog_immediate_stream FORCE"
+ sql "DROP TABLE IF EXISTS changelog_immediate_rows FORCE"
+ sql """
+ CREATE TABLE changelog_immediate_rows (k INT, v INT)
+ UNIQUE KEY(k)
+ PARTITION BY RANGE(k) (
+ PARTITION p1 VALUES LESS THAN (2),
+ PARTITION p2 VALUES LESS THAN (4)
+ )
+ DISTRIBUTED BY HASH(k) BUCKETS 2
+ PROPERTIES (
+ "replication_num" = "1",
+ "enable_unique_key_merge_on_write" = "true",
+ "changelog.enable" = "true",
+ "changelog.need_historical_value" = "true",
+ "disable_auto_compaction" = "true"
+ )
+ """
+ sql """
+ CREATE STREAM changelog_immediate_stream ON TABLE
changelog_immediate_rows
+ PROPERTIES ("type" = "detail", "show_initial_rows" = "false")
+ """
+
+ // No periodic row-count publication can initialize the index or
supply these counts.
+ sql "INSERT INTO changelog_immediate_rows VALUES (1, 10), (2, 20), (3,
30)"
+ recordIndexRows("order_index_rows_after_append")
+ qt_physical_rows_after_append """
+ SELECT count(*) FROM changelog("table" =
"changelog_immediate_rows")
+ """
+ order_qt_stream_append """
+ SELECT k, v, __DORIS_STREAM_CHANGE_TYPE_COL__ FROM
changelog_immediate_stream
+ """
+
+ // Historical images produced by MoW are counted after publish, once
per physical record.
+ sql "UPDATE changelog_immediate_rows SET v = v + 1 WHERE k IN (1, 2)"
+ recordIndexRows("order_index_rows_after_update")
+ qt_physical_rows_after_update """
+ SELECT count(*) FROM changelog("table" =
"changelog_immediate_rows")
+ """
+ order_qt_stream_update """
+ SELECT k, v, __DORIS_STREAM_CHANGE_TYPE_COL__ FROM
changelog_immediate_stream
+ """
+
+ sql "DELETE FROM changelog_immediate_rows WHERE k = 3"
+ recordIndexRows("order_index_rows_after_delete")
+ qt_physical_rows_after_delete """
+ SELECT count(*) FROM changelog("table" =
"changelog_immediate_rows")
+ """
+ order_qt_stream_delete """
+ SELECT k, v, __DORIS_STREAM_CHANGE_TYPE_COL__ FROM
changelog_immediate_stream
+ """
+ order_qt_base_after_delete "SELECT k, v FROM changelog_immediate_rows"
+
+ sql "DROP STATS changelog_immediate_rows"
+ recordIndexRows("order_index_rows_after_drop_stats")
+ sql "TRUNCATE TABLE changelog_immediate_rows"
+ recordIndexRows("order_index_rows_after_truncate")
+ sql "INSERT INTO changelog_immediate_rows VALUES (1, 100), (2, 200)"
+ recordIndexRows("order_index_rows_after_replacement_load")
+ qt_physical_rows_after_replacement_load """
+ SELECT count(*) FROM changelog("table" =
"changelog_immediate_rows")
+ """
+
+ // Two successful consumptions between periodic reports: each visible
load updates the
+ // current count independently of the stream's consumption offset and
baseline.
+ sql """
+ CREATE TABLE changelog_report_gap_sink (k INT, v INT)
+ DUPLICATE KEY(k) DISTRIBUTED BY HASH(k) BUCKETS 1
+ PROPERTIES ("replication_num" = "1")
+ """
+ sql """
+ CREATE STREAM changelog_report_gap_stream ON TABLE
changelog_immediate_rows
+ PROPERTIES ("type" = "detail", "show_initial_rows" = "false")
+ """
+ sql "INSERT INTO changelog_immediate_rows VALUES (3, 300)"
+ recordIndexRows("order_index_rows_before_first_consumption")
+ sql "INSERT INTO changelog_report_gap_sink SELECT k, v FROM
changelog_report_gap_stream"
+ qt_empty_after_first_consumption "SELECT count(*) FROM
changelog_report_gap_stream"
+ recordIndexRows("order_index_rows_after_first_consumption")
+ sql "INSERT INTO changelog_immediate_rows VALUES (0, 400)"
+ recordIndexRows("order_index_rows_between_consumptions")
+ order_qt_rows_after_second_load """
+ SELECT k, v, __DORIS_STREAM_CHANGE_TYPE_COL__ FROM
changelog_report_gap_stream
+ """
+ sql "INSERT INTO changelog_report_gap_sink SELECT k, v FROM
changelog_report_gap_stream"
+ qt_empty_after_second_consumption "SELECT count(*) FROM
changelog_report_gap_stream"
+ order_qt_consumed_rows_between_reports "SELECT k, v FROM
changelog_report_gap_sink"
+ recordIndexRows("order_index_rows_after_second_consumption")
+ } finally {
+ GetDebugPoint().disableDebugPointForAllFEs(pauseReports)
+ }
+}
diff --git
a/regression-test/suites/changelog_p0/test_cloud_changelog_subtransaction_row_count.groovy
b/regression-test/suites/changelog_p0/test_cloud_changelog_subtransaction_row_count.groovy
new file mode 100644
index 00000000000..de6a8a4c2ba
--- /dev/null
+++
b/regression-test/suites/changelog_p0/test_cloud_changelog_subtransaction_row_count.groovy
@@ -0,0 +1,76 @@
+// 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.
+
+suite("test_cloud_changelog_subtransaction_row_count", "nonConcurrent") {
+ // This exercises the MS subtransaction commit response; SN uses a
different publisher.
+ if (!isCloudMode()) {
+ return
+ }
+ def pauseReports = "FE.TabletStatMgr.updateIndexRowCount.disabled"
+ def recordIndexRows = { tag ->
+ quickRunTest(tag, "SHOW DATA FROM
cloud_changelog_subtransaction_rows", true, { row, meta ->
+ def columns = (1..meta.getColumnCount()).collectEntries { column ->
+ [(meta.getColumnLabel(column)): row[column - 1]]
+ }
+ def kind = columns.IndexName ==
"cloud_changelog_subtransaction_rows" ? "base" :
+ (columns.IndexName == "Total" ? "total" : "changelog")
+ return [kind, kind == "total" ? "-" : columns.RowCount]
+ })
+ }
+ GetDebugPoint().enableDebugPointForAllFEs(pauseReports)
+ try {
+ sql "DROP TABLE IF EXISTS cloud_changelog_subtransaction_rows FORCE"
+ sql """
+ CREATE TABLE cloud_changelog_subtransaction_rows (k INT, v INT)
+ DUPLICATE KEY(k)
+ PARTITION BY RANGE(k) (
+ PARTITION p1 VALUES LESS THAN (3),
+ PARTITION p2 VALUES LESS THAN (6)
+ )
+ DISTRIBUTED BY HASH(k) BUCKETS 2
+ PROPERTIES (
+ "replication_num" = "1",
+ "changelog.enable" = "true",
+ "disable_auto_compaction" = "true"
+ )
+ """
+ // INSERT SELECT creates separate subtransactions; INSERT VALUES can
use one buffered load.
+ sql "BEGIN"
+ sql "INSERT INTO cloud_changelog_subtransaction_rows SELECT 1, 10
UNION ALL SELECT 3, 30"
+ sql "INSERT INTO cloud_changelog_subtransaction_rows SELECT 2, 20
UNION ALL SELECT 4, 40"
+ sql "COMMIT"
+ recordIndexRows("order_index_rows_after_commit")
+ qt_physical_rows_after_commit "SELECT count(*) FROM changelog('table'
= 'cloud_changelog_subtransaction_rows')"
+ order_qt_rows_after_commit "SELECT * FROM
cloud_changelog_subtransaction_rows"
+
+ sql "BEGIN"
+ sql "INSERT INTO cloud_changelog_subtransaction_rows SELECT 5, 50"
+ sql "ROLLBACK"
+ recordIndexRows("order_index_rows_after_rollback")
+ qt_physical_rows_after_rollback "SELECT count(*) FROM
changelog('table' = 'cloud_changelog_subtransaction_rows')"
+ order_qt_rows_after_rollback "SELECT * FROM
cloud_changelog_subtransaction_rows"
+
+ sql "BEGIN"
+ sql "INSERT INTO cloud_changelog_subtransaction_rows SELECT 5, 50"
+ sql "COMMIT"
+ recordIndexRows("order_index_rows_after_next_commit")
+ qt_physical_rows_after_next_commit "SELECT count(*) FROM
changelog('table' = 'cloud_changelog_subtransaction_rows')"
+ order_qt_rows_after_next_commit "SELECT * FROM
cloud_changelog_subtransaction_rows"
+ } finally {
+ GetDebugPoint().disableDebugPointForAllFEs(pauseReports)
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]