Coverage Report

Created: 2026-08-08 02:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/tablet/tablet_meta.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "storage/tablet/tablet_meta.h"
19
20
#include <bvar/bvar.h>
21
#include <gen_cpp/Descriptors_types.h>
22
#include <gen_cpp/FrontendService_types.h>
23
#include <gen_cpp/Types_types.h>
24
#include <gen_cpp/olap_common.pb.h>
25
#include <gen_cpp/olap_file.pb.h>
26
#include <gen_cpp/segment_v2.pb.h>
27
#include <gen_cpp/types.pb.h>
28
#include <json2pb/pb_to_json.h>
29
#include <time.h>
30
31
#include <cstdint>
32
#include <memory>
33
#include <random>
34
#include <set>
35
#include <utility>
36
37
#include "cloud/cloud_meta_mgr.h"
38
#include "cloud/cloud_storage_engine.h"
39
#include "cloud/config.h"
40
#include "common/config.h"
41
#include "io/fs/file_writer.h"
42
#include "io/fs/local_file_system.h"
43
#include "storage/data_dir.h"
44
#include "storage/file_header.h"
45
#include "storage/olap_common.h"
46
#include "storage/olap_define.h"
47
#include "storage/rowset/rowset.h"
48
#include "storage/rowset/rowset_meta_manager.h"
49
#include "storage/tablet/tablet_fwd.h"
50
#include "storage/tablet/tablet_meta_manager.h"
51
#include "storage/tablet/tablet_schema_cache.h"
52
#include "storage/utils.h"
53
#include "util/debug_points.h"
54
#include "util/lru_cache.h"
55
#include "util/mem_info.h"
56
#include "util/parse_util.h"
57
#include "util/string_util.h"
58
#include "util/time.h"
59
#include "util/uid_util.h"
60
61
using std::string;
62
using std::unordered_map;
63
using std::vector;
64
65
namespace doris {
66
using namespace ErrorCode;
67
68
bvar::Adder<uint64_t> g_contains_agg_with_cache_if_eligible_total(
69
        "g_contains_agg_with_cache_if_eligible_total");
70
bvar::Adder<uint64_t> g_contains_agg_with_cache_if_eligible_partial_hit(
71
        "g_contains_agg_with_cache_if_eligible_partial_hit");
72
bvar::Adder<uint64_t> g_contains_agg_with_cache_if_eligible_full_hit(
73
        "g_contains_agg_with_cache_if_eligible_full_hit");
74
bvar::Window<bvar::Adder<uint64_t>> g_contains_agg_with_cache_if_eligible_total_minute(
75
        "g_contains_agg_with_cache_if_eligible_total_1m",
76
        &g_contains_agg_with_cache_if_eligible_total, 60);
77
bvar::Window<bvar::Adder<uint64_t>> g_contains_agg_with_cache_if_eligible_partial_hit_minute(
78
        "g_contains_agg_with_cache_if_eligible_partial_hit_1m",
79
        &g_contains_agg_with_cache_if_eligible_partial_hit, 60);
80
bvar::Window<bvar::Adder<uint64_t>> g_contains_agg_with_cache_if_eligible_full_hit_minute(
81
        "g_contains_agg_with_cache_if_eligible_full_hit_1m",
82
        &g_contains_agg_with_cache_if_eligible_full_hit, 60);
83
84
TabletMetaSharedPtr TabletMeta::create(
85
        const TCreateTabletReq& request, const TabletUid& tablet_uid, uint64_t shard_id,
86
        uint32_t next_unique_id,
87
8.33k
        const unordered_map<uint32_t, uint32_t>& col_ordinal_to_unique_id) {
88
8.33k
    std::optional<TBinlogConfig> binlog_config;
89
8.33k
    if (request.__isset.binlog_config) {
90
8.14k
        binlog_config = request.binlog_config;
91
8.14k
    }
92
8.33k
    TInvertedIndexFileStorageFormat::type inverted_index_file_storage_format =
93
8.33k
            request.inverted_index_file_storage_format;
94
95
    // We will discard this format. Don't make any further changes here.
96
8.33k
    if (request.__isset.inverted_index_storage_format) {
97
8.33k
        switch (request.inverted_index_storage_format) {
98
0
        case TInvertedIndexStorageFormat::V1:
99
0
            inverted_index_file_storage_format = TInvertedIndexFileStorageFormat::V1;
100
0
            break;
101
0
        case TInvertedIndexStorageFormat::V2:
102
0
            inverted_index_file_storage_format = TInvertedIndexFileStorageFormat::V2;
103
0
            break;
104
8.33k
        default:
105
8.33k
            break;
106
8.33k
        }
107
8.33k
    }
108
    // Decide storage format for this tablet. DEFAULT / not-set fall back to V2 on BE side.
109
8.33k
    TStorageFormat::type storage_format =
110
8.33k
            request.__isset.storage_format ? request.storage_format : TStorageFormat::V2;
111
8.33k
    return std::make_shared<TabletMeta>(
112
8.33k
            request.table_id, request.partition_id, request.tablet_id, request.replica_id,
113
8.33k
            request.tablet_schema.schema_hash, shard_id, request.tablet_schema, next_unique_id,
114
8.33k
            col_ordinal_to_unique_id, tablet_uid,
115
8.33k
            request.__isset.tablet_type ? request.tablet_type : TTabletType::TABLET_TYPE_DISK,
116
8.33k
            request.__isset.compression_type ? request.compression_type : TCompressionType::LZ4F,
117
8.33k
            request.__isset.storage_policy_id ? request.storage_policy_id : -1,
118
8.33k
            request.__isset.enable_unique_key_merge_on_write
119
8.33k
                    ? request.enable_unique_key_merge_on_write
120
8.33k
                    : false,
121
8.33k
            std::move(binlog_config), request.compaction_policy,
122
8.33k
            request.time_series_compaction_goal_size_mbytes,
123
8.33k
            request.time_series_compaction_file_count_threshold,
124
8.33k
            request.time_series_compaction_time_threshold_seconds,
125
8.33k
            request.time_series_compaction_empty_rowsets_threshold,
126
8.33k
            request.time_series_compaction_level_threshold, inverted_index_file_storage_format,
127
8.33k
            request.tde_algorithm, storage_format,
128
8.33k
            request.__isset.vertical_compaction_num_columns_per_group
129
8.33k
                    ? request.vertical_compaction_num_columns_per_group
130
8.33k
                    : 5,
131
8.33k
            request.__isset.tablet_role ? request.tablet_role : TTabletRole::TABLET_ROLE_DATA);
132
8.33k
}
133
134
341k
TabletMeta::~TabletMeta() {
135
341k
    if (_handle) {
136
339k
        TabletSchemaCache::instance()->release(_handle);
137
339k
    }
138
341k
}
139
140
TabletMeta::TabletMeta()
141
574k
        : _tablet_uid(0, 0),
142
574k
          _schema(new TabletSchema),
143
574k
          _delete_bitmap(new DeleteBitmap(_tablet_id)) {}
144
145
TabletMeta::TabletMeta(int64_t table_id, int64_t partition_id, int64_t tablet_id,
146
                       int64_t replica_id, int32_t schema_hash, int32_t shard_id,
147
                       const TTabletSchema& tablet_schema, uint32_t next_unique_id,
148
                       const std::unordered_map<uint32_t, uint32_t>& col_ordinal_to_unique_id,
149
                       TabletUid tablet_uid, TTabletType::type tabletType,
150
                       TCompressionType::type compression_type, int64_t storage_policy_id,
151
                       bool enable_unique_key_merge_on_write,
152
                       std::optional<TBinlogConfig> binlog_config, std::string compaction_policy,
153
                       int64_t time_series_compaction_goal_size_mbytes,
154
                       int64_t time_series_compaction_file_count_threshold,
155
                       int64_t time_series_compaction_time_threshold_seconds,
156
                       int64_t time_series_compaction_empty_rowsets_threshold,
157
                       int64_t time_series_compaction_level_threshold,
158
                       TInvertedIndexFileStorageFormat::type inverted_index_file_storage_format,
159
                       TEncryptionAlgorithm::type tde_algorithm,
160
                       TStorageFormat::type storage_format,
161
                       int32_t vertical_compaction_num_columns_per_group,
162
                       TTabletRole::type tablet_role)
163
8.74k
        : _tablet_uid(0, 0),
164
8.74k
          _schema(new TabletSchema),
165
8.74k
          _delete_bitmap(new DeleteBitmap(tablet_id)),
166
8.74k
          _storage_format(storage_format) {
167
8.74k
    TabletMetaPB tablet_meta_pb;
168
8.74k
    tablet_meta_pb.set_table_id(table_id);
169
8.74k
    tablet_meta_pb.set_partition_id(partition_id);
170
8.74k
    tablet_meta_pb.set_tablet_id(tablet_id);
171
8.74k
    tablet_meta_pb.set_replica_id(replica_id);
172
8.74k
    tablet_meta_pb.set_schema_hash(schema_hash);
173
8.74k
    tablet_meta_pb.set_shard_id(shard_id);
174
    // Persist the creation time, but it is not used
175
8.74k
    tablet_meta_pb.set_creation_time(time(nullptr));
176
8.74k
    tablet_meta_pb.set_cumulative_layer_point(-1);
177
8.74k
    tablet_meta_pb.set_tablet_state(PB_RUNNING);
178
8.74k
    *(tablet_meta_pb.mutable_tablet_uid()) = tablet_uid.to_proto();
179
8.74k
    tablet_meta_pb.set_tablet_type(tabletType == TTabletType::TABLET_TYPE_DISK
180
8.74k
                                           ? TabletTypePB::TABLET_TYPE_DISK
181
8.74k
                                           : TabletTypePB::TABLET_TYPE_MEMORY);
182
8.74k
    tablet_meta_pb.set_enable_unique_key_merge_on_write(enable_unique_key_merge_on_write);
183
8.74k
    tablet_meta_pb.set_storage_policy_id(storage_policy_id);
184
8.74k
    tablet_meta_pb.set_compaction_policy(compaction_policy);
185
8.74k
    tablet_meta_pb.set_time_series_compaction_goal_size_mbytes(
186
8.74k
            time_series_compaction_goal_size_mbytes);
187
8.74k
    tablet_meta_pb.set_time_series_compaction_file_count_threshold(
188
8.74k
            time_series_compaction_file_count_threshold);
189
8.74k
    tablet_meta_pb.set_time_series_compaction_time_threshold_seconds(
190
8.74k
            time_series_compaction_time_threshold_seconds);
191
8.74k
    tablet_meta_pb.set_time_series_compaction_empty_rowsets_threshold(
192
8.74k
            time_series_compaction_empty_rowsets_threshold);
193
8.74k
    tablet_meta_pb.set_time_series_compaction_level_threshold(
194
8.74k
            time_series_compaction_level_threshold);
195
8.74k
    tablet_meta_pb.set_vertical_compaction_num_columns_per_group(
196
8.74k
            vertical_compaction_num_columns_per_group);
197
8.74k
    tablet_meta_pb.set_tablet_role(tablet_role == TTabletRole::TABLET_ROLE_ROW_BINLOG
198
8.74k
                                           ? TabletRolePB::TABLET_ROLE_ROW_BINLOG
199
8.74k
                                           : TabletRolePB::TABLET_ROLE_DATA);
200
8.74k
    SchemaCreateOptions schema_create_options_for_data = {
201
8.74k
            .col_ordinal_to_unique_id = col_ordinal_to_unique_id,
202
8.74k
            .compression_type = compression_type,
203
8.74k
            .inverted_index_file_storage_format = inverted_index_file_storage_format,
204
8.74k
            .next_unique_id = next_unique_id};
205
8.74k
    TabletSchemaPB* schema_pb_for_data = tablet_meta_pb.mutable_schema();
206
8.74k
    init_schema_from_thrift(tablet_schema, schema_create_options_for_data, schema_pb_for_data);
207
208
8.74k
    tablet_meta_pb.set_in_restore_mode(false);
209
210
8.74k
    if (binlog_config.has_value()) {
211
8.08k
        BinlogConfig tmp_binlog_config;
212
8.08k
        tmp_binlog_config = binlog_config.value();
213
8.08k
        tmp_binlog_config.to_pb(tablet_meta_pb.mutable_binlog_config());
214
8.08k
    }
215
216
8.74k
    switch (tde_algorithm) {
217
0
    case doris::TEncryptionAlgorithm::AES256:
218
0
        tablet_meta_pb.set_encryption_algorithm(EncryptionAlgorithmPB::AES_256_CTR);
219
0
        break;
220
0
    case doris::TEncryptionAlgorithm::SM4:
221
0
        tablet_meta_pb.set_encryption_algorithm(EncryptionAlgorithmPB::SM4_128_CTR);
222
0
        break;
223
8.71k
    default:
224
8.71k
        tablet_meta_pb.set_encryption_algorithm(EncryptionAlgorithmPB::PLAINTEXT);
225
8.74k
    }
226
227
    // Initialize default external ColumnMeta usage according to storage format.
228
    // V2: legacy behavior, inline ColumnMetaPB only.
229
    // V3: V2 + external ColumnMetaPB (CMO) enabled by default.
230
8.68k
    switch (_storage_format) {
231
8.69k
    case TStorageFormat::V2:
232
8.69k
    case TStorageFormat::DEFAULT:
233
8.69k
    case TStorageFormat::V1:
234
8.69k
        break;
235
0
    case TStorageFormat::V3:
236
0
        schema_pb_for_data->set_storage_format(TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V3);
237
0
        _schema->set_storage_format(TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V3);
238
0
        break;
239
0
    default:
240
0
        break;
241
8.68k
    }
242
243
8.70k
    init_from_pb(tablet_meta_pb);
244
8.70k
}
245
246
TabletMeta::TabletMeta(const TabletMeta& b)
247
1.27k
        : MetadataAdder(b),
248
1.27k
          _table_id(b._table_id),
249
1.27k
          _index_id(b._index_id),
250
1.27k
          _partition_id(b._partition_id),
251
1.27k
          _tablet_id(b._tablet_id),
252
1.27k
          _replica_id(b._replica_id),
253
1.27k
          _schema_hash(b._schema_hash),
254
1.27k
          _shard_id(b._shard_id),
255
1.27k
          _creation_time(b._creation_time),
256
1.27k
          _cumulative_layer_point(b._cumulative_layer_point),
257
1.27k
          _tablet_uid(b._tablet_uid),
258
1.27k
          _tablet_type(b._tablet_type),
259
1.27k
          _tablet_state(b._tablet_state),
260
1.27k
          _schema(b._schema),
261
1.27k
          _rs_metas(b._rs_metas),
262
1.27k
          _stale_rs_metas(b._stale_rs_metas),
263
1.27k
          _in_restore_mode(b._in_restore_mode),
264
1.27k
          _preferred_rowset_type(b._preferred_rowset_type),
265
1.27k
          _storage_policy_id(b._storage_policy_id),
266
1.27k
          _cooldown_meta_id(b._cooldown_meta_id),
267
1.27k
          _enable_unique_key_merge_on_write(b._enable_unique_key_merge_on_write),
268
1.27k
          _delete_bitmap(b._delete_bitmap),
269
1.27k
          _binlog_config(b._binlog_config),
270
1.27k
          _tablet_role(b._tablet_role),
271
1.27k
          _compaction_policy(b._compaction_policy),
272
1.27k
          _time_series_compaction_goal_size_mbytes(b._time_series_compaction_goal_size_mbytes),
273
          _time_series_compaction_file_count_threshold(
274
1.27k
                  b._time_series_compaction_file_count_threshold),
275
          _time_series_compaction_time_threshold_seconds(
276
1.27k
                  b._time_series_compaction_time_threshold_seconds),
277
          _time_series_compaction_empty_rowsets_threshold(
278
1.27k
                  b._time_series_compaction_empty_rowsets_threshold),
279
1.27k
          _time_series_compaction_level_threshold(b._time_series_compaction_level_threshold),
280
          _vertical_compaction_num_columns_per_group(
281
1.27k
                  b._vertical_compaction_num_columns_per_group) {};
282
283
void TabletMeta::init_column_from_tcolumn(uint32_t unique_id, const TColumn& tcolumn,
284
28.1M
                                          ColumnPB* column) {
285
28.1M
    column->set_unique_id(unique_id);
286
28.1M
    column->set_name(tcolumn.column_name);
287
28.1M
    column->set_is_auto_increment(tcolumn.is_auto_increment);
288
28.2M
    if (tcolumn.__isset.is_on_update_current_timestamp) {
289
28.2M
        column->set_is_on_update_current_timestamp(tcolumn.is_on_update_current_timestamp);
290
28.2M
    }
291
28.1M
    string data_type;
292
28.1M
    EnumToString(TPrimitiveType, tcolumn.column_type.type, data_type);
293
28.1M
    column->set_type(data_type);
294
295
28.1M
    uint32_t length = TabletColumn::get_field_length_by_type(tcolumn.column_type.type,
296
28.1M
                                                             tcolumn.column_type.len);
297
28.1M
    column->set_length(length);
298
28.1M
    column->set_index_length(length);
299
28.1M
    column->set_precision(tcolumn.column_type.precision);
300
28.1M
    column->set_frac(tcolumn.column_type.scale);
301
302
28.1M
    if (tcolumn.__isset.result_is_nullable) {
303
2.77k
        column->set_result_is_nullable(tcolumn.result_is_nullable);
304
2.77k
    }
305
306
28.1M
    if (tcolumn.__isset.be_exec_version) {
307
28.1M
        column->set_be_exec_version(tcolumn.be_exec_version);
308
28.1M
    }
309
310
28.1M
    if (tcolumn.column_type.type == TPrimitiveType::VARCHAR ||
311
28.1M
        tcolumn.column_type.type == TPrimitiveType::STRING) {
312
11.4M
        if (!tcolumn.column_type.__isset.index_len) {
313
108
            column->set_index_length(10);
314
11.4M
        } else {
315
11.4M
            column->set_index_length(tcolumn.column_type.index_len);
316
11.4M
        }
317
11.4M
    }
318
28.1M
    if (!tcolumn.is_key) {
319
19.9M
        column->set_is_key(false);
320
19.9M
        if (tcolumn.__isset.aggregation) {
321
2.77k
            column->set_aggregation(tcolumn.aggregation);
322
19.9M
        } else {
323
19.9M
            string aggregation_type;
324
19.9M
            EnumToString(TAggregationType, tcolumn.aggregation_type, aggregation_type);
325
19.9M
            column->set_aggregation(aggregation_type);
326
19.9M
        }
327
19.9M
    } else {
328
8.26M
        column->set_is_key(true);
329
8.26M
        column->set_aggregation("NONE");
330
8.26M
    }
331
28.1M
    column->set_is_nullable(tcolumn.is_allow_null);
332
28.1M
    if (tcolumn.__isset.default_value) {
333
2.87M
        column->set_default_value(tcolumn.default_value);
334
2.87M
    }
335
28.1M
    if (tcolumn.__isset.is_bloom_filter_column) {
336
27.2k
        column->set_is_bf_column(tcolumn.is_bloom_filter_column);
337
27.2k
    }
338
28.2M
    if (tcolumn.__isset.visible) {
339
28.2M
        column->set_visible(tcolumn.visible);
340
28.2M
    }
341
30.6M
    for (size_t i = 0; i < tcolumn.children_column.size(); i++) {
342
2.46M
        ColumnPB* children_column = column->add_children_columns();
343
2.46M
        init_column_from_tcolumn(tcolumn.children_column[i].col_unique_id,
344
2.46M
                                 tcolumn.children_column[i], children_column);
345
2.46M
    }
346
28.1M
    if (tcolumn.column_type.__isset.variant_max_subcolumns_count) {
347
28.1M
        column->set_variant_max_subcolumns_count(tcolumn.column_type.variant_max_subcolumns_count);
348
28.1M
    }
349
28.1M
    if (tcolumn.__isset.pattern_type) {
350
37.9k
        switch (tcolumn.pattern_type) {
351
1.97k
        case TPatternType::MATCH_NAME:
352
1.97k
            column->set_pattern_type(PatternTypePB::MATCH_NAME);
353
1.97k
            break;
354
35.9k
        case TPatternType::MATCH_NAME_GLOB:
355
35.9k
            column->set_pattern_type(PatternTypePB::MATCH_NAME_GLOB);
356
37.9k
        }
357
37.9k
    }
358
28.1M
    if (tcolumn.__isset.variant_enable_typed_paths_to_sparse) {
359
28.1M
        column->set_variant_enable_typed_paths_to_sparse(
360
28.1M
                tcolumn.variant_enable_typed_paths_to_sparse);
361
28.1M
    }
362
28.1M
    if (tcolumn.__isset.variant_max_sparse_column_statistics_size) {
363
28.1M
        column->set_variant_max_sparse_column_statistics_size(
364
28.1M
                tcolumn.variant_max_sparse_column_statistics_size);
365
28.1M
    }
366
28.1M
    if (tcolumn.__isset.variant_sparse_hash_shard_count) {
367
25.7M
        column->set_variant_sparse_hash_shard_count(tcolumn.variant_sparse_hash_shard_count);
368
25.7M
    }
369
28.1M
    if (tcolumn.column_type.__isset.variant_enable_doc_mode) {
370
28.1M
        column->set_variant_enable_doc_mode(tcolumn.column_type.variant_enable_doc_mode);
371
28.1M
    }
372
28.1M
    if (tcolumn.__isset.variant_doc_materialization_min_rows) {
373
25.7M
        column->set_variant_doc_materialization_min_rows(
374
25.7M
                tcolumn.variant_doc_materialization_min_rows);
375
25.7M
    }
376
28.1M
    if (tcolumn.__isset.variant_doc_hash_shard_count) {
377
25.7M
        column->set_variant_doc_hash_shard_count(tcolumn.variant_doc_hash_shard_count);
378
25.7M
    }
379
28.1M
    if (tcolumn.__isset.variant_enable_nested_group) {
380
25.7M
        column->set_variant_enable_nested_group(tcolumn.variant_enable_nested_group);
381
25.7M
    }
382
28.1M
}
383
384
void TabletMeta::init_schema_from_thrift(const TTabletSchema& tablet_schema,
385
                                         const SchemaCreateOptions& schema_create_options,
386
8.71k
                                         TabletSchemaPB* tablet_schema_pb) {
387
8.71k
    const std::unordered_map<uint32_t, uint32_t>& col_ordinal_to_unique_id =
388
8.71k
            schema_create_options.col_ordinal_to_unique_id;
389
8.71k
    TCompressionType::type compression_type = schema_create_options.compression_type;
390
8.71k
    TInvertedIndexFileStorageFormat::type inverted_index_file_storage_format =
391
8.71k
            schema_create_options.inverted_index_file_storage_format;
392
8.71k
    uint32_t next_unique_id = schema_create_options.next_unique_id;
393
394
8.71k
    tablet_schema_pb->set_num_short_key_columns(tablet_schema.short_key_column_count);
395
8.71k
    tablet_schema_pb->set_num_rows_per_row_block(config::default_num_rows_per_column_file_block);
396
8.71k
    tablet_schema_pb->set_sequence_col_idx(tablet_schema.sequence_col_idx);
397
8.72k
    if (tablet_schema.__isset.binlog_tso_idx) {
398
8.72k
        tablet_schema_pb->set_binlog_tso_col_idx(tablet_schema.binlog_tso_idx);
399
8.72k
    }
400
8.73k
    if (tablet_schema.__isset.binlog_lsn_idx) {
401
8.73k
        tablet_schema_pb->set_binlog_lsn_col_idx(tablet_schema.binlog_lsn_idx);
402
8.73k
    }
403
8.73k
    if (tablet_schema.__isset.binlog_op_idx) {
404
8.73k
        tablet_schema_pb->set_binlog_op_col_idx(tablet_schema.binlog_op_idx);
405
8.73k
    }
406
8.71k
    auto p_seq_map = tablet_schema_pb->mutable_seq_map(); // ColumnGroupsPB
407
8.71k
    for (auto& it : tablet_schema.seq_map) {              // std::vector< ::doris::TColumnGroup>
408
0
        uint32_t key = it.sequence_column;
409
0
        ColumnGroupPB* cg_pb = p_seq_map->add_cg(); // ColumnGroupPB {key: {v1, v2, v3}}
410
0
        cg_pb->set_sequence_column(key);
411
0
        for (auto v : it.columns_in_group) {
412
0
            cg_pb->add_columns_in_group(v);
413
0
        }
414
0
    }
415
416
8.71k
    switch (tablet_schema.keys_type) {
417
5.06k
    case TKeysType::DUP_KEYS:
418
5.06k
        tablet_schema_pb->set_keys_type(KeysType::DUP_KEYS);
419
5.06k
        break;
420
2.60k
    case TKeysType::UNIQUE_KEYS:
421
2.60k
        tablet_schema_pb->set_keys_type(KeysType::UNIQUE_KEYS);
422
2.60k
        break;
423
762
    case TKeysType::AGG_KEYS:
424
762
        tablet_schema_pb->set_keys_type(KeysType::AGG_KEYS);
425
762
        break;
426
288
    default:
427
288
        LOG(WARNING) << "unknown tablet keys type";
428
288
        break;
429
8.71k
    }
430
431
    // compress_kind used to compress segment files
432
8.70k
    tablet_schema_pb->set_compress_kind(COMPRESS_LZ4);
433
434
    // compression_type used to compress segment page
435
8.70k
    switch (compression_type) {
436
0
    case TCompressionType::NO_COMPRESSION:
437
0
        tablet_schema_pb->set_compression_type(segment_v2::NO_COMPRESSION);
438
0
        break;
439
0
    case TCompressionType::SNAPPY:
440
0
        tablet_schema_pb->set_compression_type(segment_v2::SNAPPY);
441
0
        break;
442
0
    case TCompressionType::LZ4:
443
0
        tablet_schema_pb->set_compression_type(segment_v2::LZ4);
444
0
        break;
445
639
    case TCompressionType::LZ4F:
446
639
        tablet_schema_pb->set_compression_type(segment_v2::LZ4F);
447
639
        break;
448
0
    case TCompressionType::ZLIB:
449
0
        tablet_schema_pb->set_compression_type(segment_v2::ZLIB);
450
0
        break;
451
8.05k
    case TCompressionType::ZSTD:
452
8.05k
        tablet_schema_pb->set_compression_type(segment_v2::ZSTD);
453
8.05k
        break;
454
0
    default:
455
0
        tablet_schema_pb->set_compression_type(segment_v2::LZ4F);
456
0
        break;
457
8.70k
    }
458
459
8.68k
    switch (inverted_index_file_storage_format) {
460
0
    case TInvertedIndexFileStorageFormat::V1:
461
0
        tablet_schema_pb->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V1);
462
0
        break;
463
639
    case TInvertedIndexFileStorageFormat::V2:
464
639
        tablet_schema_pb->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V2);
465
639
        break;
466
8.04k
    case TInvertedIndexFileStorageFormat::V3:
467
8.04k
        tablet_schema_pb->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V3);
468
8.04k
        break;
469
0
    default:
470
0
        tablet_schema_pb->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V3);
471
0
        break;
472
8.68k
    }
473
474
8.68k
    switch (tablet_schema.sort_type) {
475
0
    case TSortType::type::ZORDER:
476
0
        tablet_schema_pb->set_sort_type(SortType::ZORDER);
477
0
        break;
478
8.68k
    default:
479
8.68k
        tablet_schema_pb->set_sort_type(SortType::LEXICAL);
480
8.68k
    }
481
8.69k
    tablet_schema_pb->set_sort_col_num(tablet_schema.sort_col_num);
482
8.69k
    for (const auto& i : tablet_schema.cluster_key_uids) {
483
2
        tablet_schema_pb->add_cluster_key_uids(i);
484
2
    }
485
486
    // set column information
487
8.69k
    uint32_t col_ordinal = 0;
488
8.69k
    bool has_bf_columns = false;
489
49.1k
    for (TColumn tcolumn : tablet_schema.columns) {
490
49.1k
        ColumnPB* column = tablet_schema_pb->add_column();
491
49.1k
        uint32_t unique_id = -1;
492
49.1k
        if (tcolumn.col_unique_id >= 0) {
493
47.3k
            unique_id = tcolumn.col_unique_id;
494
47.3k
        } else {
495
1.80k
            unique_id = col_ordinal_to_unique_id.at(col_ordinal);
496
1.80k
        }
497
49.1k
        init_column_from_tcolumn(unique_id, tcolumn, column);
498
499
49.1k
        col_ordinal++;
500
501
49.1k
        if (column->is_bf_column()) {
502
0
            has_bf_columns = true;
503
0
        }
504
505
49.1k
        if (tablet_schema.__isset.indexes) {
506
2
            for (auto& index : tablet_schema.indexes) {
507
2
                if (index.index_type == TIndexType::type::BLOOMFILTER ||
508
2
                    index.index_type == TIndexType::type::NGRAM_BF) {
509
0
                    DCHECK_EQ(index.columns.size(), 1);
510
0
                    if (iequal(tcolumn.column_name, index.columns[0])) {
511
0
                        column->set_is_bf_column(true);
512
0
                        break;
513
0
                    }
514
0
                }
515
2
            }
516
2
        }
517
49.1k
    }
518
519
    // copy index meta
520
8.69k
    if (tablet_schema.__isset.indexes) {
521
1
        for (auto& index : tablet_schema.indexes) {
522
1
            TabletIndexPB* index_pb = tablet_schema_pb->add_index();
523
1
            index_pb->set_index_id(index.index_id);
524
1
            index_pb->set_index_name(index.index_name);
525
            // init col_unique_id in index at be side, since col_unique_id may be -1 at fe side
526
            // get column unique id by name
527
1
            for (auto column_name : index.columns) {
528
2
                for (auto column : tablet_schema_pb->column()) {
529
2
                    if (iequal(column.name(), column_name)) {
530
1
                        index_pb->add_col_unique_id(column.unique_id());
531
1
                    }
532
2
                }
533
1
            }
534
1
            switch (index.index_type) {
535
1
            case TIndexType::BITMAP:
536
1
                index_pb->set_index_type(IndexType::BITMAP);
537
1
                break;
538
0
            case TIndexType::INVERTED:
539
0
                index_pb->set_index_type(IndexType::INVERTED);
540
0
                break;
541
0
            case TIndexType::ANN:
542
0
                index_pb->set_index_type(IndexType::ANN);
543
0
                break;
544
0
            case TIndexType::BLOOMFILTER:
545
0
                index_pb->set_index_type(IndexType::BLOOMFILTER);
546
0
                break;
547
0
            case TIndexType::NGRAM_BF:
548
0
                index_pb->set_index_type(IndexType::NGRAM_BF);
549
0
                break;
550
1
            }
551
552
1
            if (index.__isset.properties) {
553
0
                auto properties = index_pb->mutable_properties();
554
0
                for (auto kv : index.properties) {
555
0
                    (*properties)[kv.first] = kv.second;
556
0
                }
557
0
            }
558
1
        }
559
1
    }
560
561
8.69k
    tablet_schema_pb->set_next_column_unique_id(next_unique_id);
562
8.69k
    if (has_bf_columns && tablet_schema.__isset.bloom_filter_fpp) {
563
0
        tablet_schema_pb->set_bf_fpp(tablet_schema.bloom_filter_fpp);
564
0
    }
565
566
8.69k
    if (tablet_schema.__isset.is_in_memory) {
567
8.08k
        tablet_schema_pb->set_is_in_memory(tablet_schema.is_in_memory);
568
8.08k
    }
569
570
8.69k
    if (tablet_schema.__isset.disable_auto_compaction) {
571
8.09k
        tablet_schema_pb->set_disable_auto_compaction(tablet_schema.disable_auto_compaction);
572
8.09k
    }
573
574
    // Deprecated legacy flatten-nested switch. Distinct from variant_enable_nested_group.
575
8.71k
    if (tablet_schema.__isset.variant_enable_flatten_nested) {
576
8.71k
        tablet_schema_pb->set_enable_variant_flatten_nested(
577
8.71k
                tablet_schema.variant_enable_flatten_nested);
578
8.71k
    }
579
580
8.73k
    if (tablet_schema.__isset.delete_sign_idx) {
581
8.73k
        tablet_schema_pb->set_delete_sign_idx(tablet_schema.delete_sign_idx);
582
8.73k
    }
583
8.72k
    if (tablet_schema.__isset.commit_tso_col_idx) {
584
8.72k
        tablet_schema_pb->set_commit_tso_col_idx(tablet_schema.commit_tso_col_idx);
585
8.72k
    }
586
8.70k
    if (tablet_schema.__isset.store_row_column) {
587
8.70k
        tablet_schema_pb->set_store_row_column(tablet_schema.store_row_column);
588
8.70k
    }
589
8.71k
    if (tablet_schema.__isset.row_store_page_size) {
590
8.71k
        tablet_schema_pb->set_row_store_page_size(tablet_schema.row_store_page_size);
591
8.71k
    }
592
8.69k
    if (tablet_schema.__isset.storage_page_size) {
593
8.69k
        tablet_schema_pb->set_storage_page_size(tablet_schema.storage_page_size);
594
8.69k
    }
595
8.70k
    if (tablet_schema.__isset.storage_dict_page_size) {
596
8.70k
        tablet_schema_pb->set_storage_dict_page_size(tablet_schema.storage_dict_page_size);
597
8.70k
    }
598
8.71k
    if (tablet_schema.__isset.skip_write_index_on_load) {
599
8.71k
        tablet_schema_pb->set_skip_write_index_on_load(tablet_schema.skip_write_index_on_load);
600
8.71k
    }
601
8.69k
    if (tablet_schema.__isset.row_store_col_cids) {
602
8.06k
        tablet_schema_pb->mutable_row_store_column_unique_ids()->Add(
603
8.06k
                tablet_schema.row_store_col_cids.begin(), tablet_schema.row_store_col_cids.end());
604
8.06k
    }
605
8.69k
}
606
607
85.6k
void TabletMeta::remove_rowset_delete_bitmap(const RowsetId& rowset_id, const Version& version) {
608
85.6k
    if (_enable_unique_key_merge_on_write) {
609
61.6k
        delete_bitmap().remove({rowset_id, 0, 0}, {rowset_id, UINT32_MAX, 0});
610
61.6k
        if (config::enable_mow_verbose_log) {
611
0
            LOG_INFO("delete rowset delete bitmap. tablet={}, rowset={}, version={}", tablet_id(),
612
0
                     rowset_id.to_string(), version.to_string());
613
0
        }
614
61.6k
        size_t rowset_cache_version_size = delete_bitmap().remove_rowset_cache_version(rowset_id);
615
61.6k
        _check_mow_rowset_cache_version_size(rowset_cache_version_size);
616
61.6k
    }
617
85.6k
}
618
619
176
Status TabletMeta::create_from_file(const string& file_path) {
620
176
    TabletMetaPB tablet_meta_pb;
621
176
    RETURN_IF_ERROR(load_from_file(file_path, &tablet_meta_pb));
622
176
    init_from_pb(tablet_meta_pb);
623
176
    return Status::OK();
624
176
}
625
626
356
Status TabletMeta::load_from_file(const string& file_path, TabletMetaPB* tablet_meta_pb) {
627
356
    FileHeader<TabletMetaPB> file_header(file_path);
628
    // In file_header.deserialize(), it validates file length, signature, checksum of protobuf.
629
356
    RETURN_IF_ERROR(file_header.deserialize());
630
356
    try {
631
356
        tablet_meta_pb->CopyFrom(file_header.message());
632
356
    } catch (const std::exception& e) {
633
0
        LOG(WARNING) << "Failed to copy protocol buffer object: " << e.what()
634
0
                     << ", file=" << file_path;
635
0
        return Status::Error<PARSE_PROTOBUF_ERROR>(
636
0
                "fail to copy protocol buffer object. file={}, error={}", file_path, e.what());
637
0
    }
638
356
    return Status::OK();
639
356
}
640
641
6
Status TabletMeta::create_from_buffer(const uint8_t* buffer, size_t buffer_size) {
642
6
    FileHeader<TabletMetaPB> file_header(""); // empty file path
643
6
    RETURN_IF_ERROR(file_header.deserialize_from_memory(buffer, buffer_size));
644
645
2
    TabletMetaPB tablet_meta_pb;
646
2
    try {
647
2
        tablet_meta_pb.CopyFrom(file_header.message());
648
2
    } catch (const std::exception& e) {
649
0
        LOG(WARNING) << "Failed to copy protocol buffer object from buffer: " << e.what();
650
0
        return Status::Error<ErrorCode::PARSE_PROTOBUF_ERROR>(
651
0
                "fail to copy protocol buffer object from buffer. error={}", e.what());
652
0
    }
653
654
2
    init_from_pb(tablet_meta_pb);
655
2
    return Status::OK();
656
2
}
657
658
std::string TabletMeta::construct_header_file_path(const string& schema_hash_path,
659
175
                                                   int64_t tablet_id) {
660
175
    std::stringstream header_name_stream;
661
175
    header_name_stream << schema_hash_path << "/" << tablet_id << ".hdr";
662
175
    return header_name_stream.str();
663
175
}
664
665
0
Status TabletMeta::save_as_json(const string& file_path) {
666
0
    std::string json_meta;
667
0
    json2pb::Pb2JsonOptions json_options;
668
0
    json_options.pretty_json = true;
669
0
    json_options.bytes_to_base64 = true;
670
0
    to_json(&json_meta, json_options);
671
    // save to file
672
0
    io::FileWriterPtr file_writer;
673
0
    RETURN_IF_ERROR(io::global_local_filesystem()->create_file(file_path, &file_writer));
674
0
    RETURN_IF_ERROR(file_writer->append(json_meta));
675
0
    RETURN_IF_ERROR(file_writer->close());
676
0
    return Status::OK();
677
0
}
678
679
6.14k
Status TabletMeta::save(const string& file_path) {
680
6.14k
    TabletMetaPB tablet_meta_pb;
681
6.14k
    to_meta_pb(&tablet_meta_pb, false);
682
6.14k
    return TabletMeta::save(file_path, tablet_meta_pb);
683
6.14k
}
684
685
6.33k
Status TabletMeta::save(const string& file_path, const TabletMetaPB& tablet_meta_pb) {
686
6.33k
    DCHECK(!file_path.empty());
687
6.33k
    FileHeader<TabletMetaPB> file_header(file_path);
688
6.33k
    try {
689
6.33k
        file_header.mutable_message()->CopyFrom(tablet_meta_pb);
690
6.33k
    } catch (...) {
691
0
        LOG(WARNING) << "fail to copy protocol buffer object. file='" << file_path;
692
0
        return Status::Error<ErrorCode::INTERNAL_ERROR>(
693
0
                "fail to copy protocol buffer object. file={}", file_path);
694
0
    }
695
6.32k
    RETURN_IF_ERROR(file_header.prepare());
696
6.32k
    RETURN_IF_ERROR(file_header.serialize());
697
6.32k
    return Status::OK();
698
6.32k
}
699
700
30.4k
Status TabletMeta::save_meta(DataDir* data_dir) {
701
30.4k
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
702
30.4k
    return _save_meta(data_dir);
703
30.4k
}
704
705
30.4k
Status TabletMeta::_save_meta(DataDir* data_dir) {
706
    // check if tablet uid is valid
707
30.4k
    if (_tablet_uid.hi == 0 && _tablet_uid.lo == 0) {
708
0
        LOG(FATAL) << "tablet_uid is invalid"
709
0
                   << " tablet=" << tablet_id() << " _tablet_uid=" << _tablet_uid.to_string();
710
0
    }
711
30.4k
    string meta_binary;
712
713
30.4k
    auto t1 = MonotonicMicros();
714
30.4k
    serialize(&meta_binary);
715
30.4k
    auto t2 = MonotonicMicros();
716
30.4k
    Status status = TabletMetaManager::save(data_dir, tablet_id(), schema_hash(), meta_binary);
717
30.4k
    if (!status.ok()) {
718
0
        LOG(FATAL) << "fail to save tablet_meta. status=" << status << ", tablet_id=" << tablet_id()
719
0
                   << ", schema_hash=" << schema_hash();
720
0
    }
721
30.4k
    auto t3 = MonotonicMicros();
722
30.4k
    auto cost = t3 - t1;
723
30.4k
    if (cost > 1 * 1000 * 1000) {
724
0
        LOG(INFO) << "save tablet(" << tablet_id() << ") meta too slow. serialize cost " << t2 - t1
725
0
                  << "(us), serialized binary size: " << meta_binary.length()
726
0
                  << "(bytes), write rocksdb cost " << t3 - t2 << "(us)";
727
0
    }
728
30.4k
    return status;
729
30.4k
}
730
731
30.6k
void TabletMeta::serialize(string* meta_binary) {
732
30.6k
    TabletMetaPB tablet_meta_pb;
733
30.6k
    to_meta_pb(&tablet_meta_pb, false);
734
30.6k
    if (tablet_meta_pb.partition_id() <= 0) {
735
274
        LOG(WARNING) << "invalid partition id " << tablet_meta_pb.partition_id() << " tablet "
736
274
                     << tablet_meta_pb.tablet_id();
737
274
    }
738
30.6k
    DBUG_EXECUTE_IF("TabletMeta::serialize::zero_partition_id", {
739
30.6k
        long partition_id = tablet_meta_pb.partition_id();
740
30.6k
        tablet_meta_pb.set_partition_id(0);
741
30.6k
        LOG(WARNING) << "set debug point TabletMeta::serialize::zero_partition_id old="
742
30.6k
                     << partition_id << " new=" << tablet_meta_pb.DebugString();
743
30.6k
    });
744
30.6k
    bool serialize_success = tablet_meta_pb.SerializeToString(meta_binary);
745
30.6k
    if (!_rs_metas.empty() || !_stale_rs_metas.empty()) {
746
30.6k
        _avg_rs_meta_serialize_size =
747
30.6k
                meta_binary->length() / (_rs_metas.size() + _stale_rs_metas.size());
748
30.6k
        if (meta_binary->length() > config::tablet_meta_serialize_size_limit ||
749
30.6k
            !serialize_success) {
750
0
            int64_t origin_meta_size = meta_binary->length();
751
0
            int64_t stale_rowsets_num = tablet_meta_pb.stale_rs_metas().size();
752
0
            tablet_meta_pb.clear_stale_rs_metas();
753
0
            meta_binary->clear();
754
0
            serialize_success = tablet_meta_pb.SerializeToString(meta_binary);
755
0
            LOG(WARNING) << "tablet meta serialization size exceeds limit: "
756
0
                         << config::tablet_meta_serialize_size_limit
757
0
                         << " clean up stale rowsets, tablet id: " << tablet_id()
758
0
                         << " stale rowset num: " << stale_rowsets_num
759
0
                         << " serialization size before clean " << origin_meta_size
760
0
                         << " serialization size after clean " << meta_binary->length();
761
0
        }
762
30.6k
    }
763
764
30.6k
    if (!serialize_success) {
765
0
        LOG(FATAL) << "failed to serialize meta " << tablet_id();
766
0
    }
767
30.6k
}
768
769
289k
Status TabletMeta::deserialize(std::string_view meta_binary) {
770
289k
    TabletMetaPB tablet_meta_pb;
771
289k
    bool parsed = tablet_meta_pb.ParseFromArray(meta_binary.data(),
772
289k
                                                static_cast<int32_t>(meta_binary.size()));
773
289k
    if (!parsed) {
774
0
        return Status::Error<INIT_FAILED>("parse tablet meta failed");
775
0
    }
776
289k
    init_from_pb(tablet_meta_pb);
777
289k
    return Status::OK();
778
289k
}
779
780
581k
void TabletMeta::init_from_pb(const TabletMetaPB& tablet_meta_pb) {
781
581k
    _table_id = tablet_meta_pb.table_id();
782
581k
    _index_id = tablet_meta_pb.index_id();
783
581k
    _partition_id = tablet_meta_pb.partition_id();
784
581k
    _tablet_id = tablet_meta_pb.tablet_id();
785
581k
    _replica_id = tablet_meta_pb.replica_id();
786
581k
    _schema_hash = tablet_meta_pb.schema_hash();
787
581k
    _shard_id = tablet_meta_pb.shard_id();
788
581k
    _creation_time = tablet_meta_pb.creation_time();
789
581k
    _cumulative_layer_point = tablet_meta_pb.cumulative_layer_point();
790
581k
    _tablet_uid = TabletUid(tablet_meta_pb.tablet_uid());
791
581k
    _ttl_seconds = tablet_meta_pb.ttl_seconds();
792
582k
    if (tablet_meta_pb.has_tablet_type()) {
793
582k
        _tablet_type = tablet_meta_pb.tablet_type();
794
18.4E
    } else {
795
18.4E
        _tablet_type = TabletTypePB::TABLET_TYPE_DISK;
796
18.4E
    }
797
798
    // init _tablet_state
799
581k
    switch (tablet_meta_pb.tablet_state()) {
800
19.8k
    case PB_NOTREADY:
801
19.8k
        _tablet_state = TabletState::TABLET_NOTREADY;
802
19.8k
        break;
803
557k
    case PB_RUNNING:
804
557k
        _tablet_state = TabletState::TABLET_RUNNING;
805
557k
        break;
806
0
    case PB_TOMBSTONED:
807
0
        _tablet_state = TabletState::TABLET_TOMBSTONED;
808
0
        break;
809
0
    case PB_STOPPED:
810
0
        _tablet_state = TabletState::TABLET_STOPPED;
811
0
        break;
812
5.87k
    case PB_SHUTDOWN:
813
5.87k
        _tablet_state = TabletState::TABLET_SHUTDOWN;
814
5.87k
        break;
815
0
    default:
816
0
        LOG(WARNING) << "tablet has no state. tablet=" << tablet_id()
817
0
                     << ", schema_hash=" << schema_hash();
818
581k
    }
819
820
    // init _schema
821
581k
    TabletSchemaSPtr schema = std::make_shared<TabletSchema>();
822
581k
    schema->init_from_pb(tablet_meta_pb.schema());
823
581k
    if (_handle) {
824
4
        TabletSchemaCache::instance()->release(_handle);
825
4
    }
826
581k
    auto pair = TabletSchemaCache::instance()->insert(schema->to_key());
827
581k
    _handle = pair.first;
828
581k
    _schema = pair.second;
829
830
582k
    if (tablet_meta_pb.has_enable_unique_key_merge_on_write()) {
831
582k
        _enable_unique_key_merge_on_write = tablet_meta_pb.enable_unique_key_merge_on_write();
832
582k
        _delete_bitmap->set_tablet_id(_tablet_id);
833
582k
    }
834
835
    // init _rs_metas
836
581k
    for (auto& it : tablet_meta_pb.rs_metas()) {
837
495k
        RowsetMetaSharedPtr rs_meta(new RowsetMeta());
838
495k
        rs_meta->init_from_pb(it);
839
495k
        _rs_metas.emplace(rs_meta->version(), rs_meta);
840
495k
    }
841
842
    // For mow table, delete bitmap of stale rowsets has not been persisted.
843
    // When be restart, query should not read the stale rowset, otherwise duplicate keys
844
    // will be read out. Therefore, we don't add them to _stale_rs_meta for mow table.
845
582k
    if (!config::skip_loading_stale_rowset_meta && !_enable_unique_key_merge_on_write) {
846
461k
        for (auto& it : tablet_meta_pb.stale_rs_metas()) {
847
19.2k
            RowsetMetaSharedPtr rs_meta(new RowsetMeta());
848
19.2k
            rs_meta->init_from_pb(it);
849
19.2k
            _stale_rs_metas.emplace(rs_meta->version(), rs_meta);
850
19.2k
        }
851
461k
    }
852
853
582k
    if (tablet_meta_pb.has_in_restore_mode()) {
854
582k
        _in_restore_mode = tablet_meta_pb.in_restore_mode();
855
582k
    }
856
857
581k
    if (tablet_meta_pb.has_preferred_rowset_type()) {
858
574k
        _preferred_rowset_type = tablet_meta_pb.preferred_rowset_type();
859
574k
    }
860
861
581k
    _storage_policy_id = tablet_meta_pb.storage_policy_id();
862
581k
    if (tablet_meta_pb.has_cooldown_meta_id()) {
863
283k
        _cooldown_meta_id = tablet_meta_pb.cooldown_meta_id();
864
283k
    }
865
866
581k
    if (tablet_meta_pb.has_delete_bitmap()) {
867
51.3k
        int rst_ids_size = tablet_meta_pb.delete_bitmap().rowset_ids_size();
868
51.3k
        int seg_ids_size = tablet_meta_pb.delete_bitmap().segment_ids_size();
869
51.3k
        int versions_size = tablet_meta_pb.delete_bitmap().versions_size();
870
51.3k
        int seg_maps_size = tablet_meta_pb.delete_bitmap().segment_delete_bitmaps_size();
871
51.3k
        CHECK(rst_ids_size == seg_ids_size && seg_ids_size == seg_maps_size &&
872
51.3k
              seg_maps_size == versions_size);
873
55.1k
        for (int i = 0; i < rst_ids_size; ++i) {
874
3.80k
            RowsetId rst_id;
875
3.80k
            rst_id.init(tablet_meta_pb.delete_bitmap().rowset_ids(i));
876
3.80k
            auto seg_id = tablet_meta_pb.delete_bitmap().segment_ids(i);
877
3.80k
            auto ver = tablet_meta_pb.delete_bitmap().versions(i);
878
3.80k
            auto bitmap = tablet_meta_pb.delete_bitmap().segment_delete_bitmaps(i).data();
879
3.80k
            delete_bitmap().delete_bitmap[{rst_id, seg_id, ver}] = roaring::Roaring::read(bitmap);
880
3.80k
        }
881
51.3k
    }
882
883
581k
    if (tablet_meta_pb.has_binlog_config()) {
884
549k
        _binlog_config = tablet_meta_pb.binlog_config();
885
549k
    }
886
581k
    _tablet_role = tablet_meta_pb.tablet_role();
887
581k
    _compaction_policy = tablet_meta_pb.compaction_policy();
888
581k
    _time_series_compaction_goal_size_mbytes =
889
581k
            tablet_meta_pb.time_series_compaction_goal_size_mbytes();
890
581k
    _time_series_compaction_file_count_threshold =
891
581k
            tablet_meta_pb.time_series_compaction_file_count_threshold();
892
581k
    _time_series_compaction_time_threshold_seconds =
893
581k
            tablet_meta_pb.time_series_compaction_time_threshold_seconds();
894
581k
    _time_series_compaction_empty_rowsets_threshold =
895
581k
            tablet_meta_pb.time_series_compaction_empty_rowsets_threshold();
896
581k
    _time_series_compaction_level_threshold =
897
581k
            tablet_meta_pb.time_series_compaction_level_threshold();
898
581k
    _vertical_compaction_num_columns_per_group =
899
581k
            tablet_meta_pb.vertical_compaction_num_columns_per_group();
900
901
582k
    if (tablet_meta_pb.has_encryption_algorithm()) {
902
582k
        _encryption_algorithm = tablet_meta_pb.encryption_algorithm();
903
582k
    }
904
581k
}
905
906
37.1k
void TabletMeta::to_meta_pb(TabletMetaPB* tablet_meta_pb, bool cloud_get_rowset_meta) {
907
37.1k
    tablet_meta_pb->set_table_id(table_id());
908
37.1k
    tablet_meta_pb->set_index_id(index_id());
909
37.1k
    tablet_meta_pb->set_partition_id(partition_id());
910
37.1k
    tablet_meta_pb->set_tablet_id(tablet_id());
911
37.1k
    tablet_meta_pb->set_replica_id(replica_id());
912
37.1k
    tablet_meta_pb->set_schema_hash(schema_hash());
913
37.1k
    tablet_meta_pb->set_shard_id(shard_id());
914
37.1k
    tablet_meta_pb->set_creation_time(creation_time());
915
37.1k
    tablet_meta_pb->set_cumulative_layer_point(cumulative_layer_point());
916
37.1k
    *(tablet_meta_pb->mutable_tablet_uid()) = tablet_uid().to_proto();
917
37.1k
    tablet_meta_pb->set_tablet_type(_tablet_type);
918
37.1k
    tablet_meta_pb->set_ttl_seconds(_ttl_seconds);
919
37.1k
    switch (tablet_state()) {
920
97
    case TABLET_NOTREADY:
921
97
        tablet_meta_pb->set_tablet_state(PB_NOTREADY);
922
97
        break;
923
25.3k
    case TABLET_RUNNING:
924
25.3k
        tablet_meta_pb->set_tablet_state(PB_RUNNING);
925
25.3k
        break;
926
0
    case TABLET_TOMBSTONED:
927
0
        tablet_meta_pb->set_tablet_state(PB_TOMBSTONED);
928
0
        break;
929
0
    case TABLET_STOPPED:
930
0
        tablet_meta_pb->set_tablet_state(PB_STOPPED);
931
0
        break;
932
11.6k
    case TABLET_SHUTDOWN:
933
11.6k
        tablet_meta_pb->set_tablet_state(PB_SHUTDOWN);
934
11.6k
        break;
935
37.1k
    }
936
937
    // RowsetMetaPB is separated from TabletMetaPB
938
37.1k
    if (!config::is_cloud_mode() || cloud_get_rowset_meta) {
939
84.5k
        for (const auto& [_, rs] : _rs_metas) {
940
84.5k
            rs->to_rowset_pb(tablet_meta_pb->add_rs_metas());
941
84.5k
        }
942
414k
        for (const auto& [_, rs] : _stale_rs_metas) {
943
414k
            rs->to_rowset_pb(tablet_meta_pb->add_stale_rs_metas());
944
414k
        }
945
37.1k
    }
946
947
37.0k
    _schema->to_schema_pb(tablet_meta_pb->mutable_schema());
948
949
37.0k
    tablet_meta_pb->set_in_restore_mode(in_restore_mode());
950
951
    // to avoid modify tablet meta to the greatest extend
952
37.3k
    if (_preferred_rowset_type == BETA_ROWSET) {
953
37.3k
        tablet_meta_pb->set_preferred_rowset_type(_preferred_rowset_type);
954
37.3k
    }
955
37.0k
    if (_storage_policy_id > 0) {
956
5
        tablet_meta_pb->set_storage_policy_id(_storage_policy_id);
957
5
    }
958
37.0k
    if (_cooldown_meta_id.initialized()) {
959
5
        tablet_meta_pb->mutable_cooldown_meta_id()->CopyFrom(_cooldown_meta_id.to_proto());
960
5
    }
961
962
37.0k
    tablet_meta_pb->set_enable_unique_key_merge_on_write(_enable_unique_key_merge_on_write);
963
964
37.0k
    if (_enable_unique_key_merge_on_write) {
965
11.3k
        std::set<RowsetId> stale_rs_ids;
966
352k
        for (const auto& [_, rowset] : _stale_rs_metas) {
967
352k
            stale_rs_ids.insert(rowset->rowset_id());
968
352k
        }
969
11.3k
        DeleteBitmapPB* delete_bitmap_pb = tablet_meta_pb->mutable_delete_bitmap();
970
17.1k
        for (auto& [id, bitmap] : delete_bitmap().snapshot().delete_bitmap) {
971
17.1k
            auto& [rowset_id, segment_id, ver] = id;
972
17.1k
            if (stale_rs_ids.count(rowset_id) != 0) {
973
15.4k
                continue;
974
15.4k
            }
975
1.72k
            delete_bitmap_pb->add_rowset_ids(rowset_id.to_string());
976
1.72k
            delete_bitmap_pb->add_segment_ids(segment_id);
977
1.72k
            delete_bitmap_pb->add_versions(ver);
978
1.72k
            std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
979
1.72k
            bitmap.write(bitmap_data.data());
980
1.72k
            *(delete_bitmap_pb->add_segment_delete_bitmaps()) = std::move(bitmap_data);
981
1.72k
        }
982
11.3k
    }
983
37.0k
    _binlog_config.to_pb(tablet_meta_pb->mutable_binlog_config());
984
37.0k
    tablet_meta_pb->set_tablet_role(_tablet_role);
985
37.0k
    tablet_meta_pb->set_compaction_policy(compaction_policy());
986
37.0k
    tablet_meta_pb->set_time_series_compaction_goal_size_mbytes(
987
37.0k
            time_series_compaction_goal_size_mbytes());
988
37.0k
    tablet_meta_pb->set_time_series_compaction_file_count_threshold(
989
37.0k
            time_series_compaction_file_count_threshold());
990
37.0k
    tablet_meta_pb->set_time_series_compaction_time_threshold_seconds(
991
37.0k
            time_series_compaction_time_threshold_seconds());
992
37.0k
    tablet_meta_pb->set_time_series_compaction_empty_rowsets_threshold(
993
37.0k
            time_series_compaction_empty_rowsets_threshold());
994
37.0k
    tablet_meta_pb->set_time_series_compaction_level_threshold(
995
37.0k
            time_series_compaction_level_threshold());
996
37.0k
    tablet_meta_pb->set_vertical_compaction_num_columns_per_group(
997
37.0k
            vertical_compaction_num_columns_per_group());
998
999
37.0k
    tablet_meta_pb->set_encryption_algorithm(_encryption_algorithm);
1000
37.0k
}
1001
1002
4
void TabletMeta::to_json(string* json_string, json2pb::Pb2JsonOptions& options) {
1003
4
    TabletMetaPB tablet_meta_pb;
1004
4
    to_meta_pb(&tablet_meta_pb, false);
1005
4
    json2pb::ProtoMessageToJson(tablet_meta_pb, json_string, options);
1006
4
}
1007
1008
1.56M
Version TabletMeta::max_version() const {
1009
1.56M
    Version max_version = {-1, 0};
1010
5.58M
    for (const auto& [_, rs_meta] : _rs_metas) {
1011
5.58M
        if (rs_meta->end_version() > max_version.second) {
1012
1.97M
            max_version = rs_meta->version();
1013
1.97M
        }
1014
5.58M
    }
1015
1.56M
    return max_version;
1016
1.56M
}
1017
1018
1.15M
size_t TabletMeta::version_count_cross_with_range(const Version& range) const {
1019
1.15M
    size_t count = 0;
1020
2.11M
    for (const auto& [_, rs_meta] : _rs_metas) {
1021
2.11M
        if (!(range.first > rs_meta->version().second || range.second < rs_meta->version().first)) {
1022
2.11M
            count++;
1023
2.11M
        }
1024
2.11M
    }
1025
1.15M
    return count;
1026
1.15M
}
1027
1028
67.2k
Status TabletMeta::add_rs_meta(const RowsetMetaSharedPtr& rs_meta) {
1029
    // check RowsetMeta is valid
1030
776k
    for (const auto& [_, rs] : _rs_metas) {
1031
776k
        if (rs->version() == rs_meta->version()) {
1032
0
            if (rs->rowset_id() != rs_meta->rowset_id()) {
1033
0
                return Status::Error<PUSH_VERSION_ALREADY_EXIST>(
1034
0
                        "version already exist. rowset_id={}, version={}, tablet={}",
1035
0
                        rs->rowset_id().to_string(), rs->version().to_string(), tablet_id());
1036
0
            } else {
1037
                // rowsetid,version is equal, it is a duplicate req, skip it
1038
0
                return Status::OK();
1039
0
            }
1040
0
        }
1041
776k
    }
1042
67.2k
    _rs_metas.emplace(rs_meta->version(), rs_meta);
1043
67.2k
    return Status::OK();
1044
67.2k
}
1045
1046
308k
void TabletMeta::add_rowsets_unchecked(const std::vector<RowsetSharedPtr>& to_add) {
1047
321k
    for (const auto& rs : to_add) {
1048
321k
        _rs_metas.emplace(rs->rowset_meta()->version(), rs->rowset_meta());
1049
321k
    }
1050
308k
}
1051
1052
void TabletMeta::delete_rs_meta_by_version(const Version& version,
1053
840
                                           std::vector<RowsetMetaSharedPtr>* deleted_rs_metas) {
1054
840
    size_t rowset_cache_version_size = 0;
1055
840
    if (auto it = _rs_metas.find(version); it != _rs_metas.end()) {
1056
840
        if (deleted_rs_metas != nullptr) {
1057
0
            deleted_rs_metas->push_back(it->second);
1058
0
        }
1059
840
        auto rowset_id = it->second->rowset_id();
1060
840
        _rs_metas.erase(it);
1061
840
        if (_enable_unique_key_merge_on_write) {
1062
35
            rowset_cache_version_size = _delete_bitmap->remove_rowset_cache_version(rowset_id);
1063
35
        }
1064
840
        return;
1065
840
    }
1066
0
    _check_mow_rowset_cache_version_size(rowset_cache_version_size);
1067
0
}
1068
1069
void TabletMeta::modify_rs_metas(const std::vector<RowsetMetaSharedPtr>& to_add,
1070
                                 const std::vector<RowsetMetaSharedPtr>& to_delete,
1071
10.3k
                                 bool same_version) {
1072
10.3k
    size_t rowset_cache_version_size = 0;
1073
    // Remove to_delete rowsets from _rs_metas
1074
96.4k
    for (auto rs_to_del : to_delete) {
1075
96.4k
        if (auto it = _rs_metas.find(rs_to_del->version()); it != _rs_metas.end()) {
1076
96.3k
            auto rowset_id = it->second->rowset_id();
1077
96.3k
            _rs_metas.erase(it);
1078
96.3k
            if (_enable_unique_key_merge_on_write) {
1079
62.4k
                rowset_cache_version_size = _delete_bitmap->remove_rowset_cache_version(rowset_id);
1080
62.4k
            }
1081
96.3k
        }
1082
96.4k
    }
1083
10.3k
    if (!same_version) {
1084
        // put to_delete rowsets in _stale_rs_metas.
1085
96.3k
        for (auto rs_to_del : to_delete) {
1086
96.3k
            _stale_rs_metas.emplace(rs_to_del->version(), rs_to_del);
1087
96.3k
        }
1088
10.2k
    }
1089
1090
    // put to_add rowsets in _rs_metas.
1091
10.3k
    for (auto rs_to_add : to_add) {
1092
4.35k
        _rs_metas.emplace(rs_to_add->version(), rs_to_add);
1093
4.35k
    }
1094
10.3k
    _check_mow_rowset_cache_version_size(rowset_cache_version_size);
1095
10.3k
}
1096
1097
// Use the passing "rs_metas" to replace the rs meta in this tablet meta
1098
// Also clear the _stale_rs_metas because this tablet meta maybe copyied from
1099
// an existing tablet before. Add after revise, only the passing "rs_metas"
1100
// is needed.
1101
323
void TabletMeta::revise_rs_metas(std::vector<RowsetMetaSharedPtr>&& rs_metas) {
1102
323
    {
1103
323
        std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
1104
323
        _rs_metas.clear();
1105
472
        for (auto& rs_meta : rs_metas) {
1106
472
            _rs_metas.emplace(rs_meta->version(), rs_meta);
1107
472
        }
1108
323
        _stale_rs_metas.clear();
1109
323
    }
1110
323
    if (_enable_unique_key_merge_on_write) {
1111
40
        _delete_bitmap->clear_rowset_cache_version();
1112
40
    }
1113
323
}
1114
1115
// This method should call after revise_rs_metas, since new rs_metas might be a subset
1116
// of original tablet, we should revise the delete_bitmap according to current rowset.
1117
//
1118
// Delete bitmap is protected by Tablet::_meta_lock, we don't need to acquire the
1119
// TabletMeta's _meta_lock
1120
39
void TabletMeta::revise_delete_bitmap_unlocked(const DeleteBitmap& delete_bitmap) {
1121
39
    _delete_bitmap = std::make_unique<DeleteBitmap>(tablet_id());
1122
50
    for (const auto& [_, rs] : _rs_metas) {
1123
50
        DeleteBitmap rs_bm(tablet_id());
1124
50
        delete_bitmap.subset({rs->rowset_id(), 0, 0}, {rs->rowset_id(), UINT32_MAX, INT64_MAX},
1125
50
                             &rs_bm);
1126
50
        _delete_bitmap->merge(rs_bm);
1127
50
    }
1128
39
    for (const auto& [_, rs] : _stale_rs_metas) {
1129
0
        DeleteBitmap rs_bm(tablet_id());
1130
0
        delete_bitmap.subset({rs->rowset_id(), 0, 0}, {rs->rowset_id(), UINT32_MAX, INT64_MAX},
1131
0
                             &rs_bm);
1132
0
        _delete_bitmap->merge(rs_bm);
1133
0
    }
1134
39
}
1135
1136
105k
void TabletMeta::delete_stale_rs_meta_by_version(const Version& version) {
1137
105k
    _stale_rs_metas.erase(version);
1138
105k
}
1139
1140
0
RowsetMetaSharedPtr TabletMeta::acquire_rs_meta_by_version(const Version& version) const {
1141
0
    if (auto it = _rs_metas.find(version); it != _rs_metas.end()) {
1142
0
        return it->second;
1143
0
    }
1144
0
    return nullptr;
1145
0
}
1146
1147
52.9k
RowsetMetaSharedPtr TabletMeta::acquire_stale_rs_meta_by_version(const Version& version) const {
1148
52.9k
    if (auto it = _stale_rs_metas.find(version); it != _stale_rs_metas.end()) {
1149
52.9k
        return it->second;
1150
52.9k
    }
1151
8
    return nullptr;
1152
52.9k
}
1153
1154
49
Status TabletMeta::set_partition_id(int64_t partition_id) {
1155
49
    if ((_partition_id > 0 && _partition_id != partition_id) || partition_id < 1) {
1156
0
        LOG(WARNING) << "cur partition id=" << _partition_id << " new partition id=" << partition_id
1157
0
                     << " not equal";
1158
0
    }
1159
49
    _partition_id = partition_id;
1160
49
    return Status::OK();
1161
49
}
1162
1163
0
void TabletMeta::clear_stale_rowset() {
1164
0
    _stale_rs_metas.clear();
1165
0
    if (_enable_unique_key_merge_on_write) {
1166
0
        _delete_bitmap->clear_rowset_cache_version();
1167
0
    }
1168
0
}
1169
1170
0
void TabletMeta::clear_rowsets() {
1171
0
    _rs_metas.clear();
1172
0
    if (_enable_unique_key_merge_on_write) {
1173
0
        _delete_bitmap->clear_rowset_cache_version();
1174
0
    }
1175
0
}
1176
1177
71.9k
void TabletMeta::_check_mow_rowset_cache_version_size(size_t rowset_cache_version_size) {
1178
71.9k
    if (_enable_unique_key_merge_on_write && config::enable_mow_verbose_log &&
1179
71.9k
        rowset_cache_version_size > _rs_metas.size() + _stale_rs_metas.size()) {
1180
0
        std::stringstream ss;
1181
0
        auto rowset_ids = _delete_bitmap->get_rowset_cache_version();
1182
0
        std::set<std::string> tablet_rowset_ids;
1183
0
        {
1184
0
            std::shared_lock rlock(_meta_lock);
1185
0
            for (const auto& [_, rs_meta] : _rs_metas) {
1186
0
                tablet_rowset_ids.emplace(rs_meta->rowset_id().to_string());
1187
0
            }
1188
0
            for (const auto& [_, rs_meta] : _stale_rs_metas) {
1189
0
                tablet_rowset_ids.emplace(rs_meta->rowset_id().to_string());
1190
0
            }
1191
0
        }
1192
0
        for (const auto& rowset_id : rowset_ids) {
1193
0
            if (tablet_rowset_ids.find(rowset_id) == tablet_rowset_ids.end()) {
1194
0
                ss << rowset_id << ", ";
1195
0
            }
1196
0
        }
1197
        // size(rowset_cache_version) <= size(_rs_metas) + size(_stale_rs_metas) + size(_unused_rs)
1198
0
        std::string msg = fmt::format(
1199
0
                "tablet: {}, rowset_cache_version size: {}, "
1200
0
                "_rs_metas size: {}, _stale_rs_metas size: {}, delta: {}. rowset only in cache: {}",
1201
0
                _tablet_id, rowset_cache_version_size, _rs_metas.size(), _stale_rs_metas.size(),
1202
0
                rowset_cache_version_size - _rs_metas.size() - _stale_rs_metas.size(), ss.str());
1203
0
        LOG(INFO) << msg;
1204
0
    }
1205
71.9k
}
1206
1207
3
bool operator==(const TabletMeta& a, const TabletMeta& b) {
1208
3
    if (a._table_id != b._table_id) return false;
1209
3
    if (a._index_id != b._index_id) return false;
1210
3
    if (a._partition_id != b._partition_id) return false;
1211
3
    if (a._tablet_id != b._tablet_id) return false;
1212
3
    if (a._replica_id != b._replica_id) return false;
1213
3
    if (a._schema_hash != b._schema_hash) return false;
1214
3
    if (a._shard_id != b._shard_id) return false;
1215
3
    if (a._creation_time != b._creation_time) return false;
1216
3
    if (a._cumulative_layer_point != b._cumulative_layer_point) return false;
1217
3
    if (a._tablet_uid != b._tablet_uid) return false;
1218
3
    if (a._tablet_type != b._tablet_type) return false;
1219
3
    if (a._tablet_state != b._tablet_state) return false;
1220
3
    if (*a._schema != *b._schema) return false;
1221
3
    if (a._rs_metas != b._rs_metas) return false;
1222
3
    if (a._in_restore_mode != b._in_restore_mode) return false;
1223
3
    if (a._preferred_rowset_type != b._preferred_rowset_type) return false;
1224
3
    if (a._storage_policy_id != b._storage_policy_id) return false;
1225
3
    if (a._compaction_policy != b._compaction_policy) return false;
1226
3
    if (a._time_series_compaction_goal_size_mbytes != b._time_series_compaction_goal_size_mbytes)
1227
0
        return false;
1228
3
    if (a._time_series_compaction_file_count_threshold !=
1229
3
        b._time_series_compaction_file_count_threshold)
1230
0
        return false;
1231
3
    if (a._time_series_compaction_time_threshold_seconds !=
1232
3
        b._time_series_compaction_time_threshold_seconds)
1233
0
        return false;
1234
3
    if (a._time_series_compaction_empty_rowsets_threshold !=
1235
3
        b._time_series_compaction_empty_rowsets_threshold)
1236
0
        return false;
1237
3
    if (a._time_series_compaction_level_threshold != b._time_series_compaction_level_threshold)
1238
0
        return false;
1239
3
    return true;
1240
3
}
1241
1242
0
bool operator!=(const TabletMeta& a, const TabletMeta& b) {
1243
0
    return !(a == b);
1244
0
}
1245
1246
// We cannot just copy the underlying memory to construct a string
1247
// due to equivalent objects may have different padding bytes.
1248
// Reading padding bytes is undefined behavior, neither copy nor
1249
// placement new will help simplify the code.
1250
// Refer to C11 standards §6.2.6.1/6 and §6.7.9/21 for more info.
1251
5.66M
static std::string agg_cache_key(int64_t tablet_id, const DeleteBitmap::BitmapKey& bmk) {
1252
5.66M
    std::string ret(sizeof(tablet_id) + sizeof(bmk), '\0');
1253
5.66M
    *reinterpret_cast<int64_t*>(ret.data()) = tablet_id;
1254
5.66M
    auto t = reinterpret_cast<DeleteBitmap::BitmapKey*>(ret.data() + sizeof(tablet_id));
1255
5.66M
    std::get<RowsetId>(*t).version = std::get<RowsetId>(bmk).version;
1256
5.66M
    std::get<RowsetId>(*t).hi = std::get<RowsetId>(bmk).hi;
1257
5.66M
    std::get<RowsetId>(*t).mi = std::get<RowsetId>(bmk).mi;
1258
5.66M
    std::get<RowsetId>(*t).lo = std::get<RowsetId>(bmk).lo;
1259
5.66M
    std::get<1>(*t) = std::get<1>(bmk);
1260
5.66M
    std::get<2>(*t) = std::get<2>(bmk);
1261
5.66M
    return ret;
1262
5.66M
}
1263
1264
// decode cache key info from a agg_cache_key
1265
static void decode_agg_cache_key(const std::string& key_str, int64_t& tablet_id,
1266
48.0k
                                 DeleteBitmap::BitmapKey& bmk) {
1267
48.0k
    const char* ptr = key_str.data();
1268
48.0k
    tablet_id = *reinterpret_cast<const int64_t*>(ptr);
1269
48.0k
    ptr += sizeof(tablet_id);
1270
48.0k
    const auto* t = reinterpret_cast<const DeleteBitmap::BitmapKey*>(ptr);
1271
48.0k
    std::get<RowsetId>(bmk).version = std::get<RowsetId>(*t).version;
1272
48.0k
    std::get<RowsetId>(bmk).hi = std::get<RowsetId>(*t).hi;
1273
48.0k
    std::get<RowsetId>(bmk).mi = std::get<RowsetId>(*t).mi;
1274
48.0k
    std::get<RowsetId>(bmk).lo = std::get<RowsetId>(*t).lo;
1275
48.0k
    std::get<1>(bmk) = std::get<1>(*t);
1276
48.0k
    std::get<2>(bmk) = std::get<2>(*t);
1277
48.0k
}
1278
1279
DeleteBitmapAggCache::DeleteBitmapAggCache(size_t capacity)
1280
8
        : LRUCachePolicy(CachePolicy::CacheType::DELETE_BITMAP_AGG_CACHE, capacity,
1281
8
                         LRUCacheType::SIZE, config::delete_bitmap_agg_cache_stale_sweep_time_sec,
1282
8
                         /*num_shards*/ 256,
1283
8
                         /*element_count_capacity*/ 0, /*enable_prune*/ true,
1284
8
                         /*is_lru_k*/ false) {}
1285
1286
12.7M
DeleteBitmapAggCache* DeleteBitmapAggCache::instance() {
1287
12.7M
    return ExecEnv::GetInstance()->delete_bitmap_agg_cache();
1288
12.7M
}
1289
1290
8
DeleteBitmapAggCache* DeleteBitmapAggCache::create_instance(size_t capacity) {
1291
8
    return new DeleteBitmapAggCache(capacity);
1292
8
}
1293
1294
2
DeleteBitmap DeleteBitmapAggCache::snapshot(int64_t tablet_id) {
1295
2
    DeleteBitmap ret(tablet_id);
1296
48.0k
    auto collector = [&](const LRUHandle* handle) {
1297
48.0k
        auto key = handle->key().to_string();
1298
48.0k
        int64_t key_tablet_id;
1299
48.0k
        DeleteBitmap::BitmapKey bmk;
1300
48.0k
        decode_agg_cache_key(key, key_tablet_id, bmk);
1301
48.0k
        if (key_tablet_id == tablet_id) {
1302
16
            const auto& dbm = reinterpret_cast<DeleteBitmapAggCache::Value*>(handle->value)->bitmap;
1303
16
            ret.set(bmk, dbm);
1304
16
        }
1305
48.0k
    };
1306
2
    DeleteBitmapAggCache::instance()->for_each_entry(collector);
1307
2
    return ret;
1308
2
}
1309
1310
861k
DeleteBitmap::DeleteBitmap(int64_t tablet_id) : _tablet_id(tablet_id) {}
1311
1312
15.3k
DeleteBitmap::DeleteBitmap(const DeleteBitmap& o) {
1313
15.3k
    std::shared_lock l1(o.lock);
1314
15.3k
    delete_bitmap = o.delete_bitmap;
1315
15.3k
    _tablet_id = o._tablet_id;
1316
15.3k
}
1317
1318
26.8k
DeleteBitmap& DeleteBitmap::operator=(const DeleteBitmap& o) {
1319
26.8k
    if (this == &o) return *this;
1320
25.7k
    if (this < &o) {
1321
25.7k
        std::unique_lock l1(lock);
1322
25.7k
        std::shared_lock l2(o.lock);
1323
25.7k
        delete_bitmap = o.delete_bitmap;
1324
25.7k
        _tablet_id = o._tablet_id;
1325
25.7k
    } else {
1326
0
        std::shared_lock l2(o.lock);
1327
0
        std::unique_lock l1(lock);
1328
0
        delete_bitmap = o.delete_bitmap;
1329
0
        _tablet_id = o._tablet_id;
1330
0
    }
1331
25.7k
    return *this;
1332
26.8k
}
1333
1334
0
DeleteBitmap::DeleteBitmap(DeleteBitmap&& o) noexcept {
1335
0
    std::scoped_lock l(o.lock, o._rowset_cache_version_lock);
1336
0
    delete_bitmap = std::move(o.delete_bitmap);
1337
0
    _tablet_id = std::move(o._tablet_id);
1338
0
    o._rowset_cache_version.clear();
1339
0
}
1340
1341
38
DeleteBitmap& DeleteBitmap::operator=(DeleteBitmap&& o) noexcept {
1342
38
    if (this == &o) return *this;
1343
38
    std::scoped_lock l(lock, o.lock, o._rowset_cache_version_lock);
1344
38
    delete_bitmap = std::move(o.delete_bitmap);
1345
38
    _tablet_id = std::move(o._tablet_id);
1346
38
    o._rowset_cache_version.clear();
1347
38
    return *this;
1348
38
}
1349
1350
0
DeleteBitmap DeleteBitmap::from_pb(const DeleteBitmapPB& pb, int64_t tablet_id) {
1351
0
    size_t len = pb.rowset_ids().size();
1352
0
    DCHECK_EQ(len, pb.segment_ids().size());
1353
0
    DCHECK_EQ(len, pb.versions().size());
1354
0
    DeleteBitmap delete_bitmap(tablet_id);
1355
0
    for (int32_t i = 0; i < len; ++i) {
1356
0
        RowsetId rs_id;
1357
0
        rs_id.init(pb.rowset_ids(i));
1358
0
        BitmapKey key = {rs_id, pb.segment_ids(i), pb.versions(i)};
1359
0
        delete_bitmap.delete_bitmap[key] =
1360
0
                roaring::Roaring::read(pb.segment_delete_bitmaps(i).data());
1361
0
    }
1362
0
    return delete_bitmap;
1363
0
}
1364
1365
0
DeleteBitmapPB DeleteBitmap::to_pb() {
1366
0
    std::shared_lock l(lock);
1367
0
    DeleteBitmapPB ret;
1368
0
    for (const auto& [k, v] : delete_bitmap) {
1369
0
        ret.mutable_rowset_ids()->Add(std::get<0>(k).to_string());
1370
0
        ret.mutable_segment_ids()->Add(std::get<1>(k));
1371
0
        ret.mutable_versions()->Add(std::get<2>(k));
1372
0
        std::string bitmap_data(v.getSizeInBytes(), '\0');
1373
0
        v.write(bitmap_data.data());
1374
0
        ret.mutable_segment_delete_bitmaps()->Add(std::move(bitmap_data));
1375
0
    }
1376
0
    return ret;
1377
0
}
1378
1379
11.4k
DeleteBitmap DeleteBitmap::snapshot() const {
1380
11.4k
    std::shared_lock l(lock);
1381
11.4k
    return DeleteBitmap(*this);
1382
11.4k
}
1383
1384
41
DeleteBitmap DeleteBitmap::snapshot(Version version) const {
1385
    // Take snapshot first, then remove keys greater than given version.
1386
41
    DeleteBitmap snapshot = this->snapshot();
1387
41
    auto it = snapshot.delete_bitmap.begin();
1388
450
    while (it != snapshot.delete_bitmap.end()) {
1389
409
        if (std::get<2>(it->first) > version) {
1390
4
            it = snapshot.delete_bitmap.erase(it);
1391
405
        } else {
1392
405
            it++;
1393
405
        }
1394
409
    }
1395
41
    return snapshot;
1396
41
}
1397
1398
5.08M
void DeleteBitmap::add(const BitmapKey& bmk, uint32_t row_id) {
1399
5.08M
    std::lock_guard l(lock);
1400
5.08M
    delete_bitmap[bmk].add(row_id);
1401
5.08M
}
1402
1403
0
int DeleteBitmap::remove(const BitmapKey& bmk, uint32_t row_id) {
1404
0
    std::lock_guard l(lock);
1405
0
    auto it = delete_bitmap.find(bmk);
1406
0
    if (it == delete_bitmap.end()) return -1;
1407
0
    it->second.remove(row_id);
1408
0
    return 0;
1409
0
}
1410
1411
93.1k
void DeleteBitmap::remove(const BitmapKey& start, const BitmapKey& end) {
1412
93.1k
    std::lock_guard l(lock);
1413
108k
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end();) {
1414
62.4k
        auto& [k, _] = *it;
1415
62.4k
        if (k >= end) {
1416
47.3k
            break;
1417
47.3k
        }
1418
15.1k
        it = delete_bitmap.erase(it);
1419
15.1k
    }
1420
93.1k
}
1421
1422
632
void DeleteBitmap::remove(const std::vector<std::tuple<BitmapKey, BitmapKey>>& key_ranges) {
1423
632
    std::lock_guard l(lock);
1424
632
    for (auto& [start, end] : key_ranges) {
1425
1.27k
        for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end();) {
1426
1.27k
            auto& [k, _] = *it;
1427
1.27k
            if (k >= end) {
1428
632
                break;
1429
632
            }
1430
645
            it = delete_bitmap.erase(it);
1431
645
        }
1432
632
    }
1433
632
}
1434
1435
3.69M
bool DeleteBitmap::contains(const BitmapKey& bmk, uint32_t row_id) const {
1436
3.69M
    std::shared_lock l(lock);
1437
3.69M
    auto it = delete_bitmap.find(bmk);
1438
3.69M
    return it != delete_bitmap.end() && it->second.contains(row_id);
1439
3.69M
}
1440
1441
0
bool DeleteBitmap::contain_rowsets(const RowsetIdUnorderedSet& rowset_ids) const {
1442
0
    std::shared_lock l(lock);
1443
0
    return std::any_of(delete_bitmap.begin(), delete_bitmap.end(), [&](const auto& entry) {
1444
0
        return rowset_ids.contains(std::get<0>(entry.first));
1445
0
    });
1446
0
}
1447
1448
2
bool DeleteBitmap::contains_agg(const BitmapKey& bmk, uint32_t row_id) const {
1449
2
    return get_agg(bmk)->contains(row_id);
1450
2
}
1451
1452
0
bool DeleteBitmap::empty() const {
1453
0
    std::shared_lock l(lock);
1454
0
    return delete_bitmap.empty();
1455
0
}
1456
1457
286k
uint64_t DeleteBitmap::cardinality() const {
1458
286k
    std::shared_lock l(lock);
1459
286k
    uint64_t res = 0;
1460
1.40M
    for (auto entry : delete_bitmap) {
1461
1.40M
        if (std::get<1>(entry.first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1462
50.6k
            res += entry.second.cardinality();
1463
50.6k
        }
1464
1.40M
    }
1465
286k
    return res;
1466
286k
}
1467
1468
6
uint64_t DeleteBitmap::get_size() const {
1469
6
    std::shared_lock l(lock);
1470
6
    uint64_t charge = 0;
1471
44
    for (auto& [k, v] : delete_bitmap) {
1472
44
        if (std::get<1>(k) != DeleteBitmap::INVALID_SEGMENT_ID) {
1473
44
            charge += v.getSizeInBytes();
1474
44
        }
1475
44
    }
1476
6
    return charge;
1477
6
}
1478
1479
bool DeleteBitmap::contains_agg_with_cache_if_eligible(const BitmapKey& bmk,
1480
3.68M
                                                       uint32_t row_id) const {
1481
3.68M
    g_contains_agg_with_cache_if_eligible_total << 1;
1482
3.68M
    int64_t start_version {0};
1483
3.71M
    if (config::enable_mow_get_agg_by_cache) {
1484
3.71M
        auto deleter = [&](Cache::Handle* handle) {
1485
1.58M
            DeleteBitmapAggCache::instance()->release(handle);
1486
1.58M
        };
1487
3.71M
        std::unique_ptr<Cache::Handle, decltype(deleter)> dbm_handle(nullptr, deleter);
1488
3.71M
        int64_t cached_version = 0;
1489
        // 1. try to lookup the desired key directly
1490
3.71M
        dbm_handle.reset(DeleteBitmapAggCache::instance()->lookup(agg_cache_key(_tablet_id, bmk)));
1491
3.71M
        if (dbm_handle != nullptr) {
1492
1.57M
            cached_version = std::get<2>(bmk);
1493
2.13M
        } else {
1494
            // 2. if not found, try to lookup with cached version
1495
2.13M
            cached_version = _get_rowset_cache_version(bmk);
1496
2.13M
            if (cached_version > 0) {
1497
266
                if (cached_version > std::get<2>(bmk)) {
1498
19
                    cached_version = 0;
1499
247
                } else {
1500
247
                    dbm_handle.reset(DeleteBitmapAggCache::instance()->lookup(agg_cache_key(
1501
247
                            _tablet_id, {std::get<0>(bmk), std::get<1>(bmk), cached_version})));
1502
247
                }
1503
266
            }
1504
2.13M
        }
1505
3.71M
        if (dbm_handle != nullptr) {
1506
1.57M
            const auto& cached_dbm =
1507
1.57M
                    reinterpret_cast<DeleteBitmapAggCache::Value*>(
1508
1.57M
                            DeleteBitmapAggCache::instance()->value(dbm_handle.get()))
1509
1.57M
                            ->bitmap;
1510
1.57M
            if (cached_version == std::get<2>(bmk)) {
1511
1.57M
                g_contains_agg_with_cache_if_eligible_full_hit << 1;
1512
18.4E
            } else {
1513
18.4E
                g_contains_agg_with_cache_if_eligible_partial_hit << 1;
1514
18.4E
            }
1515
1.57M
            if (cached_dbm.contains(row_id)) {
1516
340
                return true;
1517
340
            }
1518
1.57M
            if (cached_version == std::get<2>(bmk)) {
1519
1.57M
                return false;
1520
1.57M
            }
1521
18.4E
            start_version = cached_version + 1;
1522
18.4E
        }
1523
3.71M
    }
1524
2.10M
    DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1525
2.10M
    std::shared_lock l(lock);
1526
2.11M
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1527
1.26M
        auto& [k, bm] = *it;
1528
1.26M
        if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1529
1.26M
            std::get<2>(k) > std::get<2>(bmk)) {
1530
1.25M
            break;
1531
1.25M
        }
1532
5.17k
        if (bm.contains(row_id)) {
1533
20
            return true;
1534
20
        }
1535
5.17k
    }
1536
2.10M
    return false;
1537
2.10M
}
1538
1539
13
void DeleteBitmap::remove_sentinel_marks() {
1540
13
    std::lock_guard l(lock);
1541
155
    for (auto it = delete_bitmap.begin(), end = delete_bitmap.end(); it != end;) {
1542
142
        if (std::get<1>(it->first) == DeleteBitmap::INVALID_SEGMENT_ID) {
1543
141
            it = delete_bitmap.erase(it);
1544
141
        } else {
1545
1
            ++it;
1546
1
        }
1547
142
    }
1548
13
}
1549
1550
8.80k
int DeleteBitmap::set(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1551
8.80k
    std::lock_guard l(lock);
1552
8.80k
    auto [_, inserted] = delete_bitmap.insert_or_assign(bmk, segment_delete_bitmap);
1553
8.80k
    return inserted;
1554
8.80k
}
1555
1556
7
int DeleteBitmap::get(const BitmapKey& bmk, roaring::Roaring* segment_delete_bitmap) const {
1557
7
    std::shared_lock l(lock);
1558
7
    auto it = delete_bitmap.find(bmk);
1559
7
    if (it == delete_bitmap.end()) return -1;
1560
7
    *segment_delete_bitmap = it->second; // copy
1561
7
    return 0;
1562
7
}
1563
1564
54
const roaring::Roaring* DeleteBitmap::get(const BitmapKey& bmk) const {
1565
54
    std::shared_lock l(lock);
1566
54
    auto it = delete_bitmap.find(bmk);
1567
54
    if (it == delete_bitmap.end()) return nullptr;
1568
41
    return &(it->second); // get address
1569
54
}
1570
1571
void DeleteBitmap::subset(const BitmapKey& start, const BitmapKey& end,
1572
64.6k
                          DeleteBitmap* subset_rowset_map) const {
1573
64.6k
    DCHECK(start < end);
1574
64.6k
    std::shared_lock l(lock);
1575
71.8k
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1576
17.5k
        auto& [k, bm] = *it;
1577
17.5k
        if (k >= end) {
1578
10.4k
            break;
1579
10.4k
        }
1580
7.14k
        subset_rowset_map->set(k, bm);
1581
7.14k
    }
1582
64.6k
}
1583
1584
void DeleteBitmap::subset(std::vector<std::pair<RowsetId, int64_t>>& rowset_ids,
1585
                          int64_t start_version, int64_t end_version,
1586
0
                          DeleteBitmap* subset_delete_map) const {
1587
0
    DCHECK(start_version <= end_version);
1588
0
    for (auto& [rowset_id, _] : rowset_ids) {
1589
0
        BitmapKey start {rowset_id, 0, 0};
1590
0
        BitmapKey end {rowset_id, UINT32_MAX, end_version + 1};
1591
0
        std::shared_lock l(lock);
1592
0
        for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1593
0
            auto& [k, bm] = *it;
1594
0
            if (k >= end) {
1595
0
                break;
1596
0
            }
1597
0
            auto version = std::get<2>(k);
1598
0
            if (version >= start_version && version <= end_version) {
1599
0
                subset_delete_map->merge(k, bm);
1600
0
                VLOG_DEBUG << "subset delete bitmap, tablet=" << _tablet_id << ", version=["
1601
0
                           << start_version << ", " << end_version
1602
0
                           << "]. rowset=" << std::get<0>(k).to_string()
1603
0
                           << ", segment=" << std::get<1>(k) << ", version=" << version
1604
0
                           << ", cardinality=" << bm.cardinality();
1605
0
            }
1606
0
        }
1607
0
    }
1608
0
}
1609
1610
void DeleteBitmap::subset_and_agg(std::vector<std::pair<RowsetId, int64_t>>& rowset_ids,
1611
                                  int64_t start_version, int64_t end_version,
1612
1
                                  DeleteBitmap* subset_delete_map) const {
1613
1
    DCHECK(start_version <= end_version);
1614
2
    for (auto& [rowset_id, segment_num] : rowset_ids) {
1615
6
        for (int64_t seg_id = 0; seg_id < segment_num; ++seg_id) {
1616
4
            BitmapKey end {rowset_id, seg_id, end_version};
1617
4
            auto bm = get_agg_without_cache(end, start_version);
1618
4
            VLOG_DEBUG << "subset delete bitmap, tablet=" << _tablet_id << ", rowset=" << rowset_id
1619
0
                       << ", segment=" << seg_id << ", version=[" << start_version << "-"
1620
0
                       << end_version << "], cardinality=" << bm->cardinality();
1621
4
            if (bm->isEmpty()) {
1622
0
                continue;
1623
0
            }
1624
4
            subset_delete_map->merge(end, *bm);
1625
4
        }
1626
2
    }
1627
1
}
1628
1629
720
size_t DeleteBitmap::get_count_with_range(const BitmapKey& start, const BitmapKey& end) const {
1630
720
    DCHECK(start < end);
1631
720
    size_t count = 0;
1632
720
    std::shared_lock l(lock);
1633
884
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1634
582
        auto& [k, bm] = *it;
1635
582
        if (k >= end) {
1636
418
            break;
1637
418
        }
1638
164
        count++;
1639
164
    }
1640
720
    return count;
1641
720
}
1642
1643
17.6k
void DeleteBitmap::merge(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1644
17.6k
    std::lock_guard l(lock);
1645
17.6k
    auto [iter, succ] = delete_bitmap.emplace(bmk, segment_delete_bitmap);
1646
17.6k
    if (!succ) {
1647
0
        iter->second |= segment_delete_bitmap;
1648
0
    }
1649
17.6k
}
1650
1651
48.8k
void DeleteBitmap::merge(const DeleteBitmap& other) {
1652
48.8k
    std::lock_guard l(lock);
1653
48.8k
    for (auto& i : other.delete_bitmap) {
1654
1.88k
        auto [j, succ] = this->delete_bitmap.insert(i);
1655
1.88k
        if (!succ) j->second |= i.second;
1656
1.88k
    }
1657
48.8k
}
1658
1659
253k
uint64_t DeleteBitmap::get_delete_bitmap_count() {
1660
253k
    std::shared_lock l(lock);
1661
253k
    uint64_t count = 0;
1662
837k
    for (auto it = delete_bitmap.begin(); it != delete_bitmap.end(); it++) {
1663
584k
        if (std::get<1>(it->first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1664
47.4k
            count++;
1665
47.4k
        }
1666
584k
    }
1667
253k
    return count;
1668
253k
}
1669
1670
void DeleteBitmap::traverse_rowset_and_version(
1671
0
        const std::function<int(const RowsetId& rowsetId, int64_t version)>& func) const {
1672
0
    std::shared_lock l(lock);
1673
0
    auto it = delete_bitmap.cbegin();
1674
0
    while (it != delete_bitmap.cend()) {
1675
0
        RowsetId rowset_id = std::get<0>(it->first);
1676
0
        int64_t version = std::get<2>(it->first);
1677
0
        int result = func(rowset_id, version);
1678
0
        if (result == -2) {
1679
            // find next <rowset, version>
1680
0
            it++;
1681
0
        } else {
1682
            // find next <rowset>
1683
0
            it = delete_bitmap.upper_bound({rowset_id, std::numeric_limits<SegmentId>::max(),
1684
0
                                            std::numeric_limits<Version>::max()});
1685
0
        }
1686
0
    }
1687
0
}
1688
1689
0
bool DeleteBitmap::has_calculated_for_multi_segments(const RowsetId& rowset_id) const {
1690
0
    return contains({rowset_id, INVALID_SEGMENT_ID, TEMP_VERSION_COMMON}, ROWSET_SENTINEL_MARK);
1691
0
}
1692
1693
124k
size_t DeleteBitmap::remove_rowset_cache_version(const RowsetId& rowset_id) {
1694
124k
    std::lock_guard l(_rowset_cache_version_lock);
1695
124k
    _rowset_cache_version.erase(rowset_id);
1696
18.4E
    VLOG_DEBUG << "remove agg cache version for tablet=" << _tablet_id
1697
18.4E
               << ", rowset=" << rowset_id.to_string();
1698
124k
    return _rowset_cache_version.size();
1699
124k
}
1700
1701
38
void DeleteBitmap::clear_rowset_cache_version() {
1702
38
    std::lock_guard l(_rowset_cache_version_lock);
1703
38
    _rowset_cache_version.clear();
1704
38
    VLOG_DEBUG << "clear agg cache version for tablet=" << _tablet_id;
1705
38
}
1706
1707
0
std::set<std::string> DeleteBitmap::get_rowset_cache_version() {
1708
0
    std::set<std::string> set;
1709
0
    std::shared_lock l(_rowset_cache_version_lock);
1710
0
    for (auto& [k, _] : _rowset_cache_version) {
1711
0
        set.insert(k.to_string());
1712
0
    }
1713
0
    return set;
1714
0
}
1715
1716
2.23M
DeleteBitmap::Version DeleteBitmap::_get_rowset_cache_version(const BitmapKey& bmk) const {
1717
2.23M
    std::shared_lock l(_rowset_cache_version_lock);
1718
2.23M
    if (auto it = _rowset_cache_version.find(std::get<0>(bmk)); it != _rowset_cache_version.end()) {
1719
14.0k
        auto& segment_cache_version = it->second;
1720
14.0k
        if (auto it1 = segment_cache_version.find(std::get<1>(bmk));
1721
14.0k
            it1 != segment_cache_version.end()) {
1722
14.0k
            return it1->second;
1723
14.0k
        }
1724
14.0k
    }
1725
2.22M
    return 0;
1726
2.23M
}
1727
1728
2
DeleteBitmap DeleteBitmap::agg_cache_snapshot() {
1729
2
    return DeleteBitmapAggCache::instance()->snapshot(_tablet_id);
1730
2
}
1731
1732
582k
void DeleteBitmap::set_tablet_id(int64_t tablet_id) {
1733
582k
    _tablet_id = tablet_id;
1734
582k
}
1735
1736
1.96M
std::shared_ptr<roaring::Roaring> DeleteBitmap::get_agg(const BitmapKey& bmk) const {
1737
1.96M
    std::string key_str = agg_cache_key(_tablet_id, bmk); // Cache key container
1738
1.96M
    CacheKey key(key_str);
1739
1.96M
    Cache::Handle* handle = DeleteBitmapAggCache::instance()->lookup(key);
1740
1741
1.96M
    DeleteBitmapAggCache::Value* val =
1742
1.96M
            handle == nullptr ? nullptr
1743
1.96M
                              : reinterpret_cast<DeleteBitmapAggCache::Value*>(
1744
1.84M
                                        DeleteBitmapAggCache::instance()->value(handle));
1745
    // FIXME: do we need a mutex here to get rid of duplicated initializations
1746
    //        of cache entries in some cases?
1747
1.96M
    if (val == nullptr) { // Renew if needed, put a new Value to cache
1748
110k
        val = new DeleteBitmapAggCache::Value();
1749
110k
        Version start_version =
1750
110k
                config::enable_mow_get_agg_by_cache ? _get_rowset_cache_version(bmk) : 0;
1751
110k
        if (start_version > 0) {
1752
13.7k
            Cache::Handle* handle2 = DeleteBitmapAggCache::instance()->lookup(
1753
13.7k
                    agg_cache_key(_tablet_id, {std::get<0>(bmk), std::get<1>(bmk), start_version}));
1754
1755
13.7k
            DBUG_EXECUTE_IF("DeleteBitmap::get_agg.cache_miss", {
1756
13.7k
                if (handle2 != nullptr) {
1757
13.7k
                    auto p = dp->param("percent", 0.3);
1758
13.7k
                    std::mt19937 gen {std::random_device {}()};
1759
13.7k
                    std::bernoulli_distribution inject_fault {p};
1760
13.7k
                    if (inject_fault(gen)) {
1761
13.7k
                        LOG_INFO("injection DeleteBitmap::get_agg.cache_miss, tablet_id={}",
1762
13.7k
                                 _tablet_id);
1763
13.7k
                        handle2 = nullptr;
1764
13.7k
                    }
1765
13.7k
                }
1766
13.7k
            });
1767
13.7k
            if (handle2 == nullptr || start_version > std::get<2>(bmk)) {
1768
121
                start_version = 0;
1769
13.6k
            } else {
1770
13.6k
                val->bitmap |= reinterpret_cast<DeleteBitmapAggCache::Value*>(
1771
13.6k
                                       DeleteBitmapAggCache::instance()->value(handle2))
1772
13.6k
                                       ->bitmap;
1773
13.6k
                VLOG_DEBUG << "get agg cache version=" << start_version
1774
4
                           << " for tablet=" << _tablet_id
1775
4
                           << ", rowset=" << std::get<0>(bmk).to_string()
1776
4
                           << ", segment=" << std::get<1>(bmk);
1777
13.6k
                start_version += 1;
1778
13.6k
            }
1779
13.7k
            if (handle2 != nullptr) {
1780
13.7k
                DeleteBitmapAggCache::instance()->release(handle2);
1781
13.7k
            }
1782
13.7k
        }
1783
110k
        {
1784
110k
            std::shared_lock l(lock);
1785
110k
            DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1786
119k
            for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1787
29.2k
                auto& [k, bm] = *it;
1788
29.2k
                if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1789
29.2k
                    std::get<2>(k) > std::get<2>(bmk)) {
1790
20.9k
                    break;
1791
20.9k
                }
1792
8.26k
                val->bitmap |= bm;
1793
8.26k
            }
1794
110k
        }
1795
110k
        size_t charge = val->bitmap.getSizeInBytes() + sizeof(DeleteBitmapAggCache::Value);
1796
110k
        handle = DeleteBitmapAggCache::instance()->insert(key, val, charge, charge,
1797
110k
                                                          CachePriority::NORMAL);
1798
110k
        if (config::enable_mow_get_agg_by_cache && !val->bitmap.isEmpty()) {
1799
20.2k
            std::lock_guard l(_rowset_cache_version_lock);
1800
            // this version is already agg
1801
20.2k
            _rowset_cache_version[std::get<0>(bmk)][std::get<1>(bmk)] = std::get<2>(bmk);
1802
20.2k
            VLOG_DEBUG << "set agg cache version=" << std::get<2>(bmk)
1803
2
                       << " for tablet=" << _tablet_id
1804
2
                       << ", rowset=" << std::get<0>(bmk).to_string()
1805
2
                       << ", segment=" << std::get<1>(bmk);
1806
20.2k
        }
1807
110k
        if (start_version > 0 && config::enable_mow_get_agg_correctness_check_core) {
1808
0
            std::shared_ptr<roaring::Roaring> bitmap = get_agg_without_cache(bmk);
1809
0
            if (val->bitmap != *bitmap) {
1810
0
                CHECK(false) << ". get agg correctness check failed for tablet=" << _tablet_id
1811
0
                             << ", rowset=" << std::get<0>(bmk).to_string()
1812
0
                             << ", segment=" << std::get<1>(bmk) << ", version=" << std::get<2>(bmk)
1813
0
                             << ". start_version from cache=" << start_version
1814
0
                             << ", delete_bitmap cardinality with cache="
1815
0
                             << val->bitmap.cardinality()
1816
0
                             << ", delete_bitmap cardinality without cache="
1817
0
                             << bitmap->cardinality();
1818
0
            }
1819
0
        }
1820
110k
    }
1821
1822
    // It is natural for the cache to reclaim the underlying memory
1823
1.96M
    return std::shared_ptr<roaring::Roaring>(
1824
1.96M
            &val->bitmap, [handle](...) { DeleteBitmapAggCache::instance()->release(handle); });
1825
1.96M
}
1826
1827
std::shared_ptr<roaring::Roaring> DeleteBitmap::get_agg_without_cache(
1828
5.24k
        const BitmapKey& bmk, const int64_t start_version) const {
1829
5.24k
    std::shared_ptr<roaring::Roaring> bitmap = std::make_shared<roaring::Roaring>();
1830
5.24k
    std::shared_lock l(lock);
1831
5.24k
    DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1832
20.8k
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1833
19.3k
        auto& [k, bm] = *it;
1834
19.3k
        if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1835
19.3k
            std::get<2>(k) > std::get<2>(bmk)) {
1836
3.74k
            break;
1837
3.74k
        }
1838
15.6k
        *bitmap |= bm;
1839
15.6k
    }
1840
5.24k
    return bitmap;
1841
5.24k
}
1842
1843
0
DeleteBitmap DeleteBitmap::diffset(const std::set<BitmapKey>& key_set) const {
1844
0
    std::shared_lock l(lock);
1845
0
    auto diff_key_set_view =
1846
0
            delete_bitmap | std::ranges::views::transform([](const auto& kv) { return kv.first; }) |
1847
0
            std::ranges::views::filter(
1848
0
                    [&key_set](const auto& key) { return !key_set.contains(key); });
1849
1850
0
    DeleteBitmap dbm(_tablet_id);
1851
0
    for (const auto& key : diff_key_set_view) {
1852
0
        const auto* bitmap = get(key);
1853
0
        DCHECK_NE(bitmap, nullptr);
1854
0
        dbm.delete_bitmap[key] = *bitmap;
1855
0
    }
1856
0
    return dbm;
1857
0
}
1858
1859
40
std::string tablet_state_name(TabletState state) {
1860
40
    switch (state) {
1861
0
    case TABLET_NOTREADY:
1862
0
        return "TABLET_NOTREADY";
1863
1864
40
    case TABLET_RUNNING:
1865
40
        return "TABLET_RUNNING";
1866
1867
0
    case TABLET_TOMBSTONED:
1868
0
        return "TABLET_TOMBSTONED";
1869
1870
0
    case TABLET_STOPPED:
1871
0
        return "TABLET_STOPPED";
1872
1873
0
    case TABLET_SHUTDOWN:
1874
0
        return "TABLET_SHUTDOWN";
1875
1876
0
    default:
1877
0
        return "TabletState(" + std::to_string(state) + ")";
1878
40
    }
1879
40
}
1880
1881
} // namespace doris