Coverage Report

Created: 2026-08-07 19:40

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
327k
TabletMeta::~TabletMeta() {
135
327k
    if (_handle) {
136
326k
        TabletSchemaCache::instance()->release(_handle);
137
326k
    }
138
327k
}
139
140
TabletMeta::TabletMeta()
141
560k
        : _tablet_uid(0, 0),
142
560k
          _schema(new TabletSchema),
143
560k
          _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.75k
        : _tablet_uid(0, 0),
164
8.75k
          _schema(new TabletSchema),
165
8.75k
          _delete_bitmap(new DeleteBitmap(tablet_id)),
166
8.75k
          _storage_format(storage_format) {
167
8.75k
    TabletMetaPB tablet_meta_pb;
168
8.75k
    tablet_meta_pb.set_table_id(table_id);
169
8.75k
    tablet_meta_pb.set_partition_id(partition_id);
170
8.75k
    tablet_meta_pb.set_tablet_id(tablet_id);
171
8.75k
    tablet_meta_pb.set_replica_id(replica_id);
172
8.75k
    tablet_meta_pb.set_schema_hash(schema_hash);
173
8.75k
    tablet_meta_pb.set_shard_id(shard_id);
174
    // Persist the creation time, but it is not used
175
8.75k
    tablet_meta_pb.set_creation_time(time(nullptr));
176
8.75k
    tablet_meta_pb.set_cumulative_layer_point(-1);
177
8.75k
    tablet_meta_pb.set_tablet_state(PB_RUNNING);
178
8.75k
    *(tablet_meta_pb.mutable_tablet_uid()) = tablet_uid.to_proto();
179
8.75k
    tablet_meta_pb.set_tablet_type(tabletType == TTabletType::TABLET_TYPE_DISK
180
8.75k
                                           ? TabletTypePB::TABLET_TYPE_DISK
181
8.75k
                                           : TabletTypePB::TABLET_TYPE_MEMORY);
182
8.75k
    tablet_meta_pb.set_enable_unique_key_merge_on_write(enable_unique_key_merge_on_write);
183
8.75k
    tablet_meta_pb.set_storage_policy_id(storage_policy_id);
184
8.75k
    tablet_meta_pb.set_compaction_policy(compaction_policy);
185
8.75k
    tablet_meta_pb.set_time_series_compaction_goal_size_mbytes(
186
8.75k
            time_series_compaction_goal_size_mbytes);
187
8.75k
    tablet_meta_pb.set_time_series_compaction_file_count_threshold(
188
8.75k
            time_series_compaction_file_count_threshold);
189
8.75k
    tablet_meta_pb.set_time_series_compaction_time_threshold_seconds(
190
8.75k
            time_series_compaction_time_threshold_seconds);
191
8.75k
    tablet_meta_pb.set_time_series_compaction_empty_rowsets_threshold(
192
8.75k
            time_series_compaction_empty_rowsets_threshold);
193
8.75k
    tablet_meta_pb.set_time_series_compaction_level_threshold(
194
8.75k
            time_series_compaction_level_threshold);
195
8.75k
    tablet_meta_pb.set_vertical_compaction_num_columns_per_group(
196
8.75k
            vertical_compaction_num_columns_per_group);
197
8.75k
    tablet_meta_pb.set_tablet_role(tablet_role == TTabletRole::TABLET_ROLE_ROW_BINLOG
198
8.75k
                                           ? TabletRolePB::TABLET_ROLE_ROW_BINLOG
199
8.75k
                                           : TabletRolePB::TABLET_ROLE_DATA);
200
8.75k
    SchemaCreateOptions schema_create_options_for_data = {
201
8.75k
            .col_ordinal_to_unique_id = col_ordinal_to_unique_id,
202
8.75k
            .compression_type = compression_type,
203
8.75k
            .inverted_index_file_storage_format = inverted_index_file_storage_format,
204
8.75k
            .next_unique_id = next_unique_id};
205
8.75k
    TabletSchemaPB* schema_pb_for_data = tablet_meta_pb.mutable_schema();
206
8.75k
    init_schema_from_thrift(tablet_schema, schema_create_options_for_data, schema_pb_for_data);
207
208
8.75k
    tablet_meta_pb.set_in_restore_mode(false);
209
210
8.75k
    if (binlog_config.has_value()) {
211
8.09k
        BinlogConfig tmp_binlog_config;
212
8.09k
        tmp_binlog_config = binlog_config.value();
213
8.09k
        tmp_binlog_config.to_pb(tablet_meta_pb.mutable_binlog_config());
214
8.09k
    }
215
216
8.75k
    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.75k
    }
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.69k
    switch (_storage_format) {
231
8.70k
    case TStorageFormat::V2:
232
8.70k
    case TStorageFormat::DEFAULT:
233
8.70k
    case TStorageFormat::V1:
234
8.70k
        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.69k
    }
242
243
8.70k
    init_from_pb(tablet_meta_pb);
244
8.70k
}
245
246
TabletMeta::TabletMeta(const TabletMeta& b)
247
1.33k
        : MetadataAdder(b),
248
1.33k
          _table_id(b._table_id),
249
1.33k
          _index_id(b._index_id),
250
1.33k
          _partition_id(b._partition_id),
251
1.33k
          _tablet_id(b._tablet_id),
252
1.33k
          _replica_id(b._replica_id),
253
1.33k
          _schema_hash(b._schema_hash),
254
1.33k
          _shard_id(b._shard_id),
255
1.33k
          _creation_time(b._creation_time),
256
1.33k
          _cumulative_layer_point(b._cumulative_layer_point),
257
1.33k
          _tablet_uid(b._tablet_uid),
258
1.33k
          _tablet_type(b._tablet_type),
259
1.33k
          _tablet_state(b._tablet_state),
260
1.33k
          _schema(b._schema),
261
1.33k
          _rs_metas(b._rs_metas),
262
1.33k
          _stale_rs_metas(b._stale_rs_metas),
263
1.33k
          _in_restore_mode(b._in_restore_mode),
264
1.33k
          _preferred_rowset_type(b._preferred_rowset_type),
265
1.33k
          _storage_policy_id(b._storage_policy_id),
266
1.33k
          _cooldown_meta_id(b._cooldown_meta_id),
267
1.33k
          _enable_unique_key_merge_on_write(b._enable_unique_key_merge_on_write),
268
1.33k
          _delete_bitmap(b._delete_bitmap),
269
1.33k
          _binlog_config(b._binlog_config),
270
1.33k
          _tablet_role(b._tablet_role),
271
1.33k
          _compaction_policy(b._compaction_policy),
272
1.33k
          _time_series_compaction_goal_size_mbytes(b._time_series_compaction_goal_size_mbytes),
273
          _time_series_compaction_file_count_threshold(
274
1.33k
                  b._time_series_compaction_file_count_threshold),
275
          _time_series_compaction_time_threshold_seconds(
276
1.33k
                  b._time_series_compaction_time_threshold_seconds),
277
          _time_series_compaction_empty_rowsets_threshold(
278
1.33k
                  b._time_series_compaction_empty_rowsets_threshold),
279
1.33k
          _time_series_compaction_level_threshold(b._time_series_compaction_level_threshold),
280
          _vertical_compaction_num_columns_per_group(
281
1.33k
                  b._vertical_compaction_num_columns_per_group) {};
282
283
void TabletMeta::init_column_from_tcolumn(uint32_t unique_id, const TColumn& tcolumn,
284
27.3M
                                          ColumnPB* column) {
285
27.3M
    column->set_unique_id(unique_id);
286
27.3M
    column->set_name(tcolumn.column_name);
287
27.3M
    column->set_is_auto_increment(tcolumn.is_auto_increment);
288
27.3M
    if (tcolumn.__isset.is_on_update_current_timestamp) {
289
27.3M
        column->set_is_on_update_current_timestamp(tcolumn.is_on_update_current_timestamp);
290
27.3M
    }
291
27.3M
    string data_type;
292
27.3M
    EnumToString(TPrimitiveType, tcolumn.column_type.type, data_type);
293
27.3M
    column->set_type(data_type);
294
295
27.3M
    uint32_t length = TabletColumn::get_field_length_by_type(tcolumn.column_type.type,
296
27.3M
                                                             tcolumn.column_type.len);
297
27.3M
    column->set_length(length);
298
27.3M
    column->set_index_length(length);
299
27.3M
    column->set_precision(tcolumn.column_type.precision);
300
27.3M
    column->set_frac(tcolumn.column_type.scale);
301
302
27.3M
    if (tcolumn.__isset.result_is_nullable) {
303
3.53k
        column->set_result_is_nullable(tcolumn.result_is_nullable);
304
3.53k
    }
305
306
27.3M
    if (tcolumn.__isset.be_exec_version) {
307
27.3M
        column->set_be_exec_version(tcolumn.be_exec_version);
308
27.3M
    }
309
310
27.3M
    if (tcolumn.column_type.type == TPrimitiveType::VARCHAR ||
311
27.3M
        tcolumn.column_type.type == TPrimitiveType::STRING) {
312
11.3M
        if (!tcolumn.column_type.__isset.index_len) {
313
108
            column->set_index_length(10);
314
11.3M
        } else {
315
11.3M
            column->set_index_length(tcolumn.column_type.index_len);
316
11.3M
        }
317
11.3M
    }
318
27.3M
    if (!tcolumn.is_key) {
319
19.2M
        column->set_is_key(false);
320
19.2M
        if (tcolumn.__isset.aggregation) {
321
3.53k
            column->set_aggregation(tcolumn.aggregation);
322
19.2M
        } else {
323
19.2M
            string aggregation_type;
324
19.2M
            EnumToString(TAggregationType, tcolumn.aggregation_type, aggregation_type);
325
19.2M
            column->set_aggregation(aggregation_type);
326
19.2M
        }
327
19.2M
    } else {
328
8.14M
        column->set_is_key(true);
329
8.14M
        column->set_aggregation("NONE");
330
8.14M
    }
331
27.3M
    column->set_is_nullable(tcolumn.is_allow_null);
332
27.3M
    if (tcolumn.__isset.default_value) {
333
2.70M
        column->set_default_value(tcolumn.default_value);
334
2.70M
    }
335
27.3M
    if (tcolumn.__isset.is_bloom_filter_column) {
336
16.5k
        column->set_is_bf_column(tcolumn.is_bloom_filter_column);
337
16.5k
    }
338
27.3M
    if (tcolumn.__isset.visible) {
339
27.3M
        column->set_visible(tcolumn.visible);
340
27.3M
    }
341
29.8M
    for (size_t i = 0; i < tcolumn.children_column.size(); i++) {
342
2.44M
        ColumnPB* children_column = column->add_children_columns();
343
2.44M
        init_column_from_tcolumn(tcolumn.children_column[i].col_unique_id,
344
2.44M
                                 tcolumn.children_column[i], children_column);
345
2.44M
    }
346
27.4M
    if (tcolumn.column_type.__isset.variant_max_subcolumns_count) {
347
27.4M
        column->set_variant_max_subcolumns_count(tcolumn.column_type.variant_max_subcolumns_count);
348
27.4M
    }
349
27.3M
    if (tcolumn.__isset.pattern_type) {
350
38.5k
        switch (tcolumn.pattern_type) {
351
2.07k
        case TPatternType::MATCH_NAME:
352
2.07k
            column->set_pattern_type(PatternTypePB::MATCH_NAME);
353
2.07k
            break;
354
36.4k
        case TPatternType::MATCH_NAME_GLOB:
355
36.4k
            column->set_pattern_type(PatternTypePB::MATCH_NAME_GLOB);
356
38.5k
        }
357
38.5k
    }
358
27.3M
    if (tcolumn.__isset.variant_enable_typed_paths_to_sparse) {
359
27.3M
        column->set_variant_enable_typed_paths_to_sparse(
360
27.3M
                tcolumn.variant_enable_typed_paths_to_sparse);
361
27.3M
    }
362
27.3M
    if (tcolumn.__isset.variant_max_sparse_column_statistics_size) {
363
27.3M
        column->set_variant_max_sparse_column_statistics_size(
364
27.3M
                tcolumn.variant_max_sparse_column_statistics_size);
365
27.3M
    }
366
27.3M
    if (tcolumn.__isset.variant_sparse_hash_shard_count) {
367
24.9M
        column->set_variant_sparse_hash_shard_count(tcolumn.variant_sparse_hash_shard_count);
368
24.9M
    }
369
27.4M
    if (tcolumn.column_type.__isset.variant_enable_doc_mode) {
370
27.4M
        column->set_variant_enable_doc_mode(tcolumn.column_type.variant_enable_doc_mode);
371
27.4M
    }
372
27.3M
    if (tcolumn.__isset.variant_doc_materialization_min_rows) {
373
24.9M
        column->set_variant_doc_materialization_min_rows(
374
24.9M
                tcolumn.variant_doc_materialization_min_rows);
375
24.9M
    }
376
27.3M
    if (tcolumn.__isset.variant_doc_hash_shard_count) {
377
24.9M
        column->set_variant_doc_hash_shard_count(tcolumn.variant_doc_hash_shard_count);
378
24.9M
    }
379
27.3M
    if (tcolumn.__isset.variant_enable_nested_group) {
380
24.9M
        column->set_variant_enable_nested_group(tcolumn.variant_enable_nested_group);
381
24.9M
    }
382
27.3M
}
383
384
void TabletMeta::init_schema_from_thrift(const TTabletSchema& tablet_schema,
385
                                         const SchemaCreateOptions& schema_create_options,
386
8.73k
                                         TabletSchemaPB* tablet_schema_pb) {
387
8.73k
    const std::unordered_map<uint32_t, uint32_t>& col_ordinal_to_unique_id =
388
8.73k
            schema_create_options.col_ordinal_to_unique_id;
389
8.73k
    TCompressionType::type compression_type = schema_create_options.compression_type;
390
8.73k
    TInvertedIndexFileStorageFormat::type inverted_index_file_storage_format =
391
8.73k
            schema_create_options.inverted_index_file_storage_format;
392
8.73k
    uint32_t next_unique_id = schema_create_options.next_unique_id;
393
394
8.73k
    tablet_schema_pb->set_num_short_key_columns(tablet_schema.short_key_column_count);
395
8.73k
    tablet_schema_pb->set_num_rows_per_row_block(config::default_num_rows_per_column_file_block);
396
8.73k
    tablet_schema_pb->set_sequence_col_idx(tablet_schema.sequence_col_idx);
397
8.75k
    if (tablet_schema.__isset.binlog_tso_idx) {
398
8.75k
        tablet_schema_pb->set_binlog_tso_col_idx(tablet_schema.binlog_tso_idx);
399
8.75k
    }
400
8.75k
    if (tablet_schema.__isset.binlog_lsn_idx) {
401
8.75k
        tablet_schema_pb->set_binlog_lsn_col_idx(tablet_schema.binlog_lsn_idx);
402
8.75k
    }
403
8.74k
    if (tablet_schema.__isset.binlog_op_idx) {
404
8.74k
        tablet_schema_pb->set_binlog_op_col_idx(tablet_schema.binlog_op_idx);
405
8.74k
    }
406
8.73k
    auto p_seq_map = tablet_schema_pb->mutable_seq_map(); // ColumnGroupsPB
407
8.73k
    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.73k
    switch (tablet_schema.keys_type) {
417
5.08k
    case TKeysType::DUP_KEYS:
418
5.08k
        tablet_schema_pb->set_keys_type(KeysType::DUP_KEYS);
419
5.08k
        break;
420
2.61k
    case TKeysType::UNIQUE_KEYS:
421
2.61k
        tablet_schema_pb->set_keys_type(KeysType::UNIQUE_KEYS);
422
2.61k
        break;
423
756
    case TKeysType::AGG_KEYS:
424
756
        tablet_schema_pb->set_keys_type(KeysType::AGG_KEYS);
425
756
        break;
426
288
    default:
427
288
        LOG(WARNING) << "unknown tablet keys type";
428
288
        break;
429
8.73k
    }
430
431
    // compress_kind used to compress segment files
432
8.71k
    tablet_schema_pb->set_compress_kind(COMPRESS_LZ4);
433
434
    // compression_type used to compress segment page
435
8.71k
    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.07k
    case TCompressionType::ZSTD:
452
8.07k
        tablet_schema_pb->set_compression_type(segment_v2::ZSTD);
453
8.07k
        break;
454
0
    default:
455
0
        tablet_schema_pb->set_compression_type(segment_v2::LZ4F);
456
0
        break;
457
8.71k
    }
458
459
8.71k
    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.06k
    case TInvertedIndexFileStorageFormat::V3:
467
8.06k
        tablet_schema_pb->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V3);
468
8.06k
        break;
469
0
    default:
470
0
        tablet_schema_pb->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V3);
471
0
        break;
472
8.71k
    }
473
474
8.70k
    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.70k
    default:
479
8.70k
        tablet_schema_pb->set_sort_type(SortType::LEXICAL);
480
8.70k
    }
481
8.70k
    tablet_schema_pb->set_sort_col_num(tablet_schema.sort_col_num);
482
8.70k
    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.70k
    uint32_t col_ordinal = 0;
488
8.70k
    bool has_bf_columns = false;
489
49.2k
    for (TColumn tcolumn : tablet_schema.columns) {
490
49.2k
        ColumnPB* column = tablet_schema_pb->add_column();
491
49.2k
        uint32_t unique_id = -1;
492
49.2k
        if (tcolumn.col_unique_id >= 0) {
493
47.3k
            unique_id = tcolumn.col_unique_id;
494
47.3k
        } else {
495
1.92k
            unique_id = col_ordinal_to_unique_id.at(col_ordinal);
496
1.92k
        }
497
49.2k
        init_column_from_tcolumn(unique_id, tcolumn, column);
498
499
49.2k
        col_ordinal++;
500
501
49.2k
        if (column->is_bf_column()) {
502
0
            has_bf_columns = true;
503
0
        }
504
505
49.2k
        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.2k
    }
518
519
    // copy index meta
520
8.70k
    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.70k
    tablet_schema_pb->set_next_column_unique_id(next_unique_id);
562
8.70k
    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.70k
    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.70k
    if (tablet_schema.__isset.disable_auto_compaction) {
571
8.10k
        tablet_schema_pb->set_disable_auto_compaction(tablet_schema.disable_auto_compaction);
572
8.10k
    }
573
574
    // Deprecated legacy flatten-nested switch. Distinct from variant_enable_nested_group.
575
8.74k
    if (tablet_schema.__isset.variant_enable_flatten_nested) {
576
8.74k
        tablet_schema_pb->set_enable_variant_flatten_nested(
577
8.74k
                tablet_schema.variant_enable_flatten_nested);
578
8.74k
    }
579
580
8.74k
    if (tablet_schema.__isset.delete_sign_idx) {
581
8.74k
        tablet_schema_pb->set_delete_sign_idx(tablet_schema.delete_sign_idx);
582
8.74k
    }
583
8.71k
    if (tablet_schema.__isset.commit_tso_col_idx) {
584
8.71k
        tablet_schema_pb->set_commit_tso_col_idx(tablet_schema.commit_tso_col_idx);
585
8.71k
    }
586
8.72k
    if (tablet_schema.__isset.store_row_column) {
587
8.72k
        tablet_schema_pb->set_store_row_column(tablet_schema.store_row_column);
588
8.72k
    }
589
8.73k
    if (tablet_schema.__isset.row_store_page_size) {
590
8.73k
        tablet_schema_pb->set_row_store_page_size(tablet_schema.row_store_page_size);
591
8.73k
    }
592
8.71k
    if (tablet_schema.__isset.storage_page_size) {
593
8.71k
        tablet_schema_pb->set_storage_page_size(tablet_schema.storage_page_size);
594
8.71k
    }
595
8.71k
    if (tablet_schema.__isset.storage_dict_page_size) {
596
8.71k
        tablet_schema_pb->set_storage_dict_page_size(tablet_schema.storage_dict_page_size);
597
8.71k
    }
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.70k
    if (tablet_schema.__isset.row_store_col_cids) {
602
8.10k
        tablet_schema_pb->mutable_row_store_column_unique_ids()->Add(
603
8.10k
                tablet_schema.row_store_col_cids.begin(), tablet_schema.row_store_col_cids.end());
604
8.10k
    }
605
8.70k
}
606
607
87.4k
void TabletMeta::remove_rowset_delete_bitmap(const RowsetId& rowset_id, const Version& version) {
608
87.4k
    if (_enable_unique_key_merge_on_write) {
609
62.4k
        delete_bitmap().remove({rowset_id, 0, 0}, {rowset_id, UINT32_MAX, 0});
610
62.4k
        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
62.4k
        size_t rowset_cache_version_size = delete_bitmap().remove_rowset_cache_version(rowset_id);
615
62.4k
        _check_mow_rowset_cache_version_size(rowset_cache_version_size);
616
62.4k
    }
617
87.4k
}
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.50k
Status TabletMeta::save(const string& file_path) {
680
6.50k
    TabletMetaPB tablet_meta_pb;
681
6.50k
    to_meta_pb(&tablet_meta_pb, false);
682
6.50k
    return TabletMeta::save(file_path, tablet_meta_pb);
683
6.50k
}
684
685
6.68k
Status TabletMeta::save(const string& file_path, const TabletMetaPB& tablet_meta_pb) {
686
6.68k
    DCHECK(!file_path.empty());
687
6.68k
    FileHeader<TabletMetaPB> file_header(file_path);
688
6.68k
    try {
689
6.68k
        file_header.mutable_message()->CopyFrom(tablet_meta_pb);
690
6.68k
    } 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.67k
    RETURN_IF_ERROR(file_header.prepare());
696
6.67k
    RETURN_IF_ERROR(file_header.serialize());
697
6.67k
    return Status::OK();
698
6.67k
}
699
700
30.0k
Status TabletMeta::save_meta(DataDir* data_dir) {
701
30.0k
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
702
30.0k
    return _save_meta(data_dir);
703
30.0k
}
704
705
29.9k
Status TabletMeta::_save_meta(DataDir* data_dir) {
706
    // check if tablet uid is valid
707
29.9k
    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
29.9k
    string meta_binary;
712
713
29.9k
    auto t1 = MonotonicMicros();
714
29.9k
    serialize(&meta_binary);
715
29.9k
    auto t2 = MonotonicMicros();
716
29.9k
    Status status = TabletMetaManager::save(data_dir, tablet_id(), schema_hash(), meta_binary);
717
29.9k
    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
29.9k
    auto t3 = MonotonicMicros();
722
29.9k
    auto cost = t3 - t1;
723
29.9k
    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
29.9k
    return status;
729
29.9k
}
730
731
30.2k
void TabletMeta::serialize(string* meta_binary) {
732
30.2k
    TabletMetaPB tablet_meta_pb;
733
30.2k
    to_meta_pb(&tablet_meta_pb, false);
734
30.2k
    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.2k
    DBUG_EXECUTE_IF("TabletMeta::serialize::zero_partition_id", {
739
30.2k
        long partition_id = tablet_meta_pb.partition_id();
740
30.2k
        tablet_meta_pb.set_partition_id(0);
741
30.2k
        LOG(WARNING) << "set debug point TabletMeta::serialize::zero_partition_id old="
742
30.2k
                     << partition_id << " new=" << tablet_meta_pb.DebugString();
743
30.2k
    });
744
30.2k
    bool serialize_success = tablet_meta_pb.SerializeToString(meta_binary);
745
30.2k
    if (!_rs_metas.empty() || !_stale_rs_metas.empty()) {
746
30.1k
        _avg_rs_meta_serialize_size =
747
30.1k
                meta_binary->length() / (_rs_metas.size() + _stale_rs_metas.size());
748
30.1k
        if (meta_binary->length() > config::tablet_meta_serialize_size_limit ||
749
30.1k
            !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.1k
    }
763
764
30.2k
    if (!serialize_success) {
765
0
        LOG(FATAL) << "failed to serialize meta " << tablet_id();
766
0
    }
767
30.2k
}
768
769
285k
Status TabletMeta::deserialize(std::string_view meta_binary) {
770
285k
    TabletMetaPB tablet_meta_pb;
771
285k
    bool parsed = tablet_meta_pb.ParseFromArray(meta_binary.data(),
772
285k
                                                static_cast<int32_t>(meta_binary.size()));
773
285k
    if (!parsed) {
774
0
        return Status::Error<INIT_FAILED>("parse tablet meta failed");
775
0
    }
776
285k
    init_from_pb(tablet_meta_pb);
777
285k
    return Status::OK();
778
285k
}
779
780
567k
void TabletMeta::init_from_pb(const TabletMetaPB& tablet_meta_pb) {
781
567k
    _table_id = tablet_meta_pb.table_id();
782
567k
    _index_id = tablet_meta_pb.index_id();
783
567k
    _partition_id = tablet_meta_pb.partition_id();
784
567k
    _tablet_id = tablet_meta_pb.tablet_id();
785
567k
    _replica_id = tablet_meta_pb.replica_id();
786
567k
    _schema_hash = tablet_meta_pb.schema_hash();
787
567k
    _shard_id = tablet_meta_pb.shard_id();
788
567k
    _creation_time = tablet_meta_pb.creation_time();
789
567k
    _cumulative_layer_point = tablet_meta_pb.cumulative_layer_point();
790
567k
    _tablet_uid = TabletUid(tablet_meta_pb.tablet_uid());
791
567k
    _ttl_seconds = tablet_meta_pb.ttl_seconds();
792
568k
    if (tablet_meta_pb.has_tablet_type()) {
793
568k
        _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
567k
    switch (tablet_meta_pb.tablet_state()) {
800
19.2k
    case PB_NOTREADY:
801
19.2k
        _tablet_state = TabletState::TABLET_NOTREADY;
802
19.2k
        break;
803
541k
    case PB_RUNNING:
804
541k
        _tablet_state = TabletState::TABLET_RUNNING;
805
541k
        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
7.24k
    case PB_SHUTDOWN:
813
7.24k
        _tablet_state = TabletState::TABLET_SHUTDOWN;
814
7.24k
        break;
815
0
    default:
816
0
        LOG(WARNING) << "tablet has no state. tablet=" << tablet_id()
817
0
                     << ", schema_hash=" << schema_hash();
818
567k
    }
819
820
    // init _schema
821
567k
    TabletSchemaSPtr schema = std::make_shared<TabletSchema>();
822
567k
    schema->init_from_pb(tablet_meta_pb.schema());
823
567k
    if (_handle) {
824
4
        TabletSchemaCache::instance()->release(_handle);
825
4
    }
826
567k
    auto pair = TabletSchemaCache::instance()->insert(schema->to_key());
827
567k
    _handle = pair.first;
828
567k
    _schema = pair.second;
829
830
569k
    if (tablet_meta_pb.has_enable_unique_key_merge_on_write()) {
831
569k
        _enable_unique_key_merge_on_write = tablet_meta_pb.enable_unique_key_merge_on_write();
832
569k
        _delete_bitmap->set_tablet_id(_tablet_id);
833
569k
    }
834
835
    // init _rs_metas
836
567k
    for (auto& it : tablet_meta_pb.rs_metas()) {
837
492k
        RowsetMetaSharedPtr rs_meta(new RowsetMeta());
838
492k
        rs_meta->init_from_pb(it);
839
492k
        _rs_metas.emplace(rs_meta->version(), rs_meta);
840
492k
    }
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
568k
    if (!config::skip_loading_stale_rowset_meta && !_enable_unique_key_merge_on_write) {
846
447k
        for (auto& it : tablet_meta_pb.stale_rs_metas()) {
847
18.2k
            RowsetMetaSharedPtr rs_meta(new RowsetMeta());
848
18.2k
            rs_meta->init_from_pb(it);
849
18.2k
            _stale_rs_metas.emplace(rs_meta->version(), rs_meta);
850
18.2k
        }
851
447k
    }
852
853
568k
    if (tablet_meta_pb.has_in_restore_mode()) {
854
568k
        _in_restore_mode = tablet_meta_pb.in_restore_mode();
855
568k
    }
856
857
567k
    if (tablet_meta_pb.has_preferred_rowset_type()) {
858
560k
        _preferred_rowset_type = tablet_meta_pb.preferred_rowset_type();
859
560k
    }
860
861
567k
    _storage_policy_id = tablet_meta_pb.storage_policy_id();
862
567k
    if (tablet_meta_pb.has_cooldown_meta_id()) {
863
273k
        _cooldown_meta_id = tablet_meta_pb.cooldown_meta_id();
864
273k
    }
865
866
567k
    if (tablet_meta_pb.has_delete_bitmap()) {
867
50.8k
        int rst_ids_size = tablet_meta_pb.delete_bitmap().rowset_ids_size();
868
50.8k
        int seg_ids_size = tablet_meta_pb.delete_bitmap().segment_ids_size();
869
50.8k
        int versions_size = tablet_meta_pb.delete_bitmap().versions_size();
870
50.8k
        int seg_maps_size = tablet_meta_pb.delete_bitmap().segment_delete_bitmaps_size();
871
50.8k
        CHECK(rst_ids_size == seg_ids_size && seg_ids_size == seg_maps_size &&
872
50.8k
              seg_maps_size == versions_size);
873
54.6k
        for (int i = 0; i < rst_ids_size; ++i) {
874
3.79k
            RowsetId rst_id;
875
3.79k
            rst_id.init(tablet_meta_pb.delete_bitmap().rowset_ids(i));
876
3.79k
            auto seg_id = tablet_meta_pb.delete_bitmap().segment_ids(i);
877
3.79k
            auto ver = tablet_meta_pb.delete_bitmap().versions(i);
878
3.79k
            auto bitmap = tablet_meta_pb.delete_bitmap().segment_delete_bitmaps(i).data();
879
3.79k
            delete_bitmap().delete_bitmap[{rst_id, seg_id, ver}] = roaring::Roaring::read(bitmap);
880
3.79k
        }
881
50.8k
    }
882
883
567k
    if (tablet_meta_pb.has_binlog_config()) {
884
537k
        _binlog_config = tablet_meta_pb.binlog_config();
885
537k
    }
886
567k
    _tablet_role = tablet_meta_pb.tablet_role();
887
567k
    _compaction_policy = tablet_meta_pb.compaction_policy();
888
567k
    _time_series_compaction_goal_size_mbytes =
889
567k
            tablet_meta_pb.time_series_compaction_goal_size_mbytes();
890
567k
    _time_series_compaction_file_count_threshold =
891
567k
            tablet_meta_pb.time_series_compaction_file_count_threshold();
892
567k
    _time_series_compaction_time_threshold_seconds =
893
567k
            tablet_meta_pb.time_series_compaction_time_threshold_seconds();
894
567k
    _time_series_compaction_empty_rowsets_threshold =
895
567k
            tablet_meta_pb.time_series_compaction_empty_rowsets_threshold();
896
567k
    _time_series_compaction_level_threshold =
897
567k
            tablet_meta_pb.time_series_compaction_level_threshold();
898
567k
    _vertical_compaction_num_columns_per_group =
899
567k
            tablet_meta_pb.vertical_compaction_num_columns_per_group();
900
901
568k
    if (tablet_meta_pb.has_encryption_algorithm()) {
902
568k
        _encryption_algorithm = tablet_meta_pb.encryption_algorithm();
903
568k
    }
904
567k
}
905
906
37.0k
void TabletMeta::to_meta_pb(TabletMetaPB* tablet_meta_pb, bool cloud_get_rowset_meta) {
907
37.0k
    tablet_meta_pb->set_table_id(table_id());
908
37.0k
    tablet_meta_pb->set_index_id(index_id());
909
37.0k
    tablet_meta_pb->set_partition_id(partition_id());
910
37.0k
    tablet_meta_pb->set_tablet_id(tablet_id());
911
37.0k
    tablet_meta_pb->set_replica_id(replica_id());
912
37.0k
    tablet_meta_pb->set_schema_hash(schema_hash());
913
37.0k
    tablet_meta_pb->set_shard_id(shard_id());
914
37.0k
    tablet_meta_pb->set_creation_time(creation_time());
915
37.0k
    tablet_meta_pb->set_cumulative_layer_point(cumulative_layer_point());
916
37.0k
    *(tablet_meta_pb->mutable_tablet_uid()) = tablet_uid().to_proto();
917
37.0k
    tablet_meta_pb->set_tablet_type(_tablet_type);
918
37.0k
    tablet_meta_pb->set_ttl_seconds(_ttl_seconds);
919
37.0k
    switch (tablet_state()) {
920
99
    case TABLET_NOTREADY:
921
99
        tablet_meta_pb->set_tablet_state(PB_NOTREADY);
922
99
        break;
923
25.0k
    case TABLET_RUNNING:
924
25.0k
        tablet_meta_pb->set_tablet_state(PB_RUNNING);
925
25.0k
        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.9k
    case TABLET_SHUTDOWN:
933
11.9k
        tablet_meta_pb->set_tablet_state(PB_SHUTDOWN);
934
11.9k
        break;
935
37.0k
    }
936
937
    // RowsetMetaPB is separated from TabletMetaPB
938
37.0k
    if (!config::is_cloud_mode() || cloud_get_rowset_meta) {
939
85.7k
        for (const auto& [_, rs] : _rs_metas) {
940
85.7k
            rs->to_rowset_pb(tablet_meta_pb->add_rs_metas());
941
85.7k
        }
942
415k
        for (const auto& [_, rs] : _stale_rs_metas) {
943
415k
            rs->to_rowset_pb(tablet_meta_pb->add_stale_rs_metas());
944
415k
        }
945
37.0k
    }
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.2k
    if (_preferred_rowset_type == BETA_ROWSET) {
953
37.2k
        tablet_meta_pb->set_preferred_rowset_type(_preferred_rowset_type);
954
37.2k
    }
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.5k
        std::set<RowsetId> stale_rs_ids;
966
357k
        for (const auto& [_, rowset] : _stale_rs_metas) {
967
357k
            stale_rs_ids.insert(rowset->rowset_id());
968
357k
        }
969
11.5k
        DeleteBitmapPB* delete_bitmap_pb = tablet_meta_pb->mutable_delete_bitmap();
970
17.7k
        for (auto& [id, bitmap] : delete_bitmap().snapshot().delete_bitmap) {
971
17.7k
            auto& [rowset_id, segment_id, ver] = id;
972
17.7k
            if (stale_rs_ids.count(rowset_id) != 0) {
973
15.9k
                continue;
974
15.9k
            }
975
1.77k
            delete_bitmap_pb->add_rowset_ids(rowset_id.to_string());
976
1.77k
            delete_bitmap_pb->add_segment_ids(segment_id);
977
1.77k
            delete_bitmap_pb->add_versions(ver);
978
1.77k
            std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
979
1.77k
            bitmap.write(bitmap_data.data());
980
1.77k
            *(delete_bitmap_pb->add_segment_delete_bitmaps()) = std::move(bitmap_data);
981
1.77k
        }
982
11.5k
    }
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.61M
Version TabletMeta::max_version() const {
1009
1.61M
    Version max_version = {-1, 0};
1010
5.72M
    for (const auto& [_, rs_meta] : _rs_metas) {
1011
5.72M
        if (rs_meta->end_version() > max_version.second) {
1012
2.03M
            max_version = rs_meta->version();
1013
2.03M
        }
1014
5.72M
    }
1015
1.61M
    return max_version;
1016
1.61M
}
1017
1018
1.13M
size_t TabletMeta::version_count_cross_with_range(const Version& range) const {
1019
1.13M
    size_t count = 0;
1020
2.09M
    for (const auto& [_, rs_meta] : _rs_metas) {
1021
2.09M
        if (!(range.first > rs_meta->version().second || range.second < rs_meta->version().first)) {
1022
2.09M
            count++;
1023
2.09M
        }
1024
2.09M
    }
1025
1.13M
    return count;
1026
1.13M
}
1027
1028
66.1k
Status TabletMeta::add_rs_meta(const RowsetMetaSharedPtr& rs_meta) {
1029
    // check RowsetMeta is valid
1030
770k
    for (const auto& [_, rs] : _rs_metas) {
1031
770k
        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
770k
    }
1042
66.1k
    _rs_metas.emplace(rs_meta->version(), rs_meta);
1043
66.1k
    return Status::OK();
1044
66.1k
}
1045
1046
312k
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
312k
}
1051
1052
void TabletMeta::delete_rs_meta_by_version(const Version& version,
1053
822
                                           std::vector<RowsetMetaSharedPtr>* deleted_rs_metas) {
1054
822
    size_t rowset_cache_version_size = 0;
1055
823
    if (auto it = _rs_metas.find(version); it != _rs_metas.end()) {
1056
823
        if (deleted_rs_metas != nullptr) {
1057
0
            deleted_rs_metas->push_back(it->second);
1058
0
        }
1059
823
        auto rowset_id = it->second->rowset_id();
1060
823
        _rs_metas.erase(it);
1061
823
        if (_enable_unique_key_merge_on_write) {
1062
41
            rowset_cache_version_size = _delete_bitmap->remove_rowset_cache_version(rowset_id);
1063
41
        }
1064
823
        return;
1065
823
    }
1066
18.4E
    _check_mow_rowset_cache_version_size(rowset_cache_version_size);
1067
18.4E
}
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.5k
    for (auto rs_to_del : to_delete) {
1075
96.5k
        if (auto it = _rs_metas.find(rs_to_del->version()); it != _rs_metas.end()) {
1076
96.2k
            auto rowset_id = it->second->rowset_id();
1077
96.2k
            _rs_metas.erase(it);
1078
96.2k
            if (_enable_unique_key_merge_on_write) {
1079
62.5k
                rowset_cache_version_size = _delete_bitmap->remove_rowset_cache_version(rowset_id);
1080
62.5k
            }
1081
96.2k
        }
1082
96.5k
    }
1083
10.3k
    if (!same_version) {
1084
        // put to_delete rowsets in _stale_rs_metas.
1085
96.4k
        for (auto rs_to_del : to_delete) {
1086
96.4k
            _stale_rs_metas.emplace(rs_to_del->version(), rs_to_del);
1087
96.4k
        }
1088
10.2k
    }
1089
1090
    // put to_add rowsets in _rs_metas.
1091
10.3k
    for (auto rs_to_add : to_add) {
1092
4.42k
        _rs_metas.emplace(rs_to_add->version(), rs_to_add);
1093
4.42k
    }
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
325
void TabletMeta::revise_rs_metas(std::vector<RowsetMetaSharedPtr>&& rs_metas) {
1102
325
    {
1103
325
        std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
1104
325
        _rs_metas.clear();
1105
478
        for (auto& rs_meta : rs_metas) {
1106
478
            _rs_metas.emplace(rs_meta->version(), rs_meta);
1107
478
        }
1108
325
        _stale_rs_metas.clear();
1109
325
    }
1110
325
    if (_enable_unique_key_merge_on_write) {
1111
40
        _delete_bitmap->clear_rowset_cache_version();
1112
40
    }
1113
325
}
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
41
void TabletMeta::revise_delete_bitmap_unlocked(const DeleteBitmap& delete_bitmap) {
1121
41
    _delete_bitmap = std::make_unique<DeleteBitmap>(tablet_id());
1122
48
    for (const auto& [_, rs] : _rs_metas) {
1123
48
        DeleteBitmap rs_bm(tablet_id());
1124
48
        delete_bitmap.subset({rs->rowset_id(), 0, 0}, {rs->rowset_id(), UINT32_MAX, INT64_MAX},
1125
48
                             &rs_bm);
1126
48
        _delete_bitmap->merge(rs_bm);
1127
48
    }
1128
41
    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
41
}
1135
1136
106k
void TabletMeta::delete_stale_rs_meta_by_version(const Version& version) {
1137
106k
    _stale_rs_metas.erase(version);
1138
106k
}
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.2k
RowsetMetaSharedPtr TabletMeta::acquire_stale_rs_meta_by_version(const Version& version) const {
1148
52.2k
    if (auto it = _stale_rs_metas.find(version); it != _stale_rs_metas.end()) {
1149
52.2k
        return it->second;
1150
52.2k
    }
1151
8
    return nullptr;
1152
52.2k
}
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
72.7k
void TabletMeta::_check_mow_rowset_cache_version_size(size_t rowset_cache_version_size) {
1178
72.7k
    if (_enable_unique_key_merge_on_write && config::enable_mow_verbose_log &&
1179
72.7k
        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
72.7k
}
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.67M
static std::string agg_cache_key(int64_t tablet_id, const DeleteBitmap::BitmapKey& bmk) {
1252
5.67M
    std::string ret(sizeof(tablet_id) + sizeof(bmk), '\0');
1253
5.67M
    *reinterpret_cast<int64_t*>(ret.data()) = tablet_id;
1254
5.67M
    auto t = reinterpret_cast<DeleteBitmap::BitmapKey*>(ret.data() + sizeof(tablet_id));
1255
5.67M
    std::get<RowsetId>(*t).version = std::get<RowsetId>(bmk).version;
1256
5.67M
    std::get<RowsetId>(*t).hi = std::get<RowsetId>(bmk).hi;
1257
5.67M
    std::get<RowsetId>(*t).mi = std::get<RowsetId>(bmk).mi;
1258
5.67M
    std::get<RowsetId>(*t).lo = std::get<RowsetId>(bmk).lo;
1259
5.67M
    std::get<1>(*t) = std::get<1>(bmk);
1260
5.67M
    std::get<2>(*t) = std::get<2>(bmk);
1261
5.67M
    return ret;
1262
5.67M
}
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.9k
                                 DeleteBitmap::BitmapKey& bmk) {
1267
48.9k
    const char* ptr = key_str.data();
1268
48.9k
    tablet_id = *reinterpret_cast<const int64_t*>(ptr);
1269
48.9k
    ptr += sizeof(tablet_id);
1270
48.9k
    const auto* t = reinterpret_cast<const DeleteBitmap::BitmapKey*>(ptr);
1271
48.9k
    std::get<RowsetId>(bmk).version = std::get<RowsetId>(*t).version;
1272
48.9k
    std::get<RowsetId>(bmk).hi = std::get<RowsetId>(*t).hi;
1273
48.9k
    std::get<RowsetId>(bmk).mi = std::get<RowsetId>(*t).mi;
1274
48.9k
    std::get<RowsetId>(bmk).lo = std::get<RowsetId>(*t).lo;
1275
48.9k
    std::get<1>(bmk) = std::get<1>(*t);
1276
48.9k
    std::get<2>(bmk) = std::get<2>(*t);
1277
48.9k
}
1278
1279
DeleteBitmapAggCache::DeleteBitmapAggCache(size_t capacity)
1280
7
        : LRUCachePolicy(CachePolicy::CacheType::DELETE_BITMAP_AGG_CACHE, capacity,
1281
7
                         LRUCacheType::SIZE, config::delete_bitmap_agg_cache_stale_sweep_time_sec,
1282
7
                         /*num_shards*/ 256,
1283
7
                         /*element_count_capacity*/ 0, /*enable_prune*/ true,
1284
7
                         /*is_lru_k*/ false) {}
1285
1286
12.4M
DeleteBitmapAggCache* DeleteBitmapAggCache::instance() {
1287
12.4M
    return ExecEnv::GetInstance()->delete_bitmap_agg_cache();
1288
12.4M
}
1289
1290
7
DeleteBitmapAggCache* DeleteBitmapAggCache::create_instance(size_t capacity) {
1291
7
    return new DeleteBitmapAggCache(capacity);
1292
7
}
1293
1294
2
DeleteBitmap DeleteBitmapAggCache::snapshot(int64_t tablet_id) {
1295
2
    DeleteBitmap ret(tablet_id);
1296
48.9k
    auto collector = [&](const LRUHandle* handle) {
1297
48.9k
        auto key = handle->key().to_string();
1298
48.9k
        int64_t key_tablet_id;
1299
48.9k
        DeleteBitmap::BitmapKey bmk;
1300
48.9k
        decode_agg_cache_key(key, key_tablet_id, bmk);
1301
48.9k
        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.9k
    };
1306
2
    DeleteBitmapAggCache::instance()->for_each_entry(collector);
1307
2
    return ret;
1308
2
}
1309
1310
818k
DeleteBitmap::DeleteBitmap(int64_t tablet_id) : _tablet_id(tablet_id) {}
1311
1312
13.5k
DeleteBitmap::DeleteBitmap(const DeleteBitmap& o) {
1313
13.5k
    std::shared_lock l1(o.lock);
1314
13.5k
    delete_bitmap = o.delete_bitmap;
1315
13.5k
    _tablet_id = o._tablet_id;
1316
13.5k
}
1317
1318
26.9k
DeleteBitmap& DeleteBitmap::operator=(const DeleteBitmap& o) {
1319
26.9k
    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
18.4E
    } else {
1326
18.4E
        std::shared_lock l2(o.lock);
1327
18.4E
        std::unique_lock l1(lock);
1328
18.4E
        delete_bitmap = o.delete_bitmap;
1329
18.4E
        _tablet_id = o._tablet_id;
1330
18.4E
    }
1331
25.7k
    return *this;
1332
26.9k
}
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
40
DeleteBitmap& DeleteBitmap::operator=(DeleteBitmap&& o) noexcept {
1342
40
    if (this == &o) return *this;
1343
40
    std::scoped_lock l(lock, o.lock, o._rowset_cache_version_lock);
1344
40
    delete_bitmap = std::move(o.delete_bitmap);
1345
40
    _tablet_id = std::move(o._tablet_id);
1346
40
    o._rowset_cache_version.clear();
1347
40
    return *this;
1348
40
}
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.5k
DeleteBitmap DeleteBitmap::snapshot() const {
1380
11.5k
    std::shared_lock l(lock);
1381
11.5k
    return DeleteBitmap(*this);
1382
11.5k
}
1383
1384
43
DeleteBitmap DeleteBitmap::snapshot(Version version) const {
1385
    // Take snapshot first, then remove keys greater than given version.
1386
43
    DeleteBitmap snapshot = this->snapshot();
1387
43
    auto it = snapshot.delete_bitmap.begin();
1388
452
    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
43
    return snapshot;
1396
43
}
1397
1398
4.91M
void DeleteBitmap::add(const BitmapKey& bmk, uint32_t row_id) {
1399
4.91M
    std::lock_guard l(lock);
1400
4.91M
    delete_bitmap[bmk].add(row_id);
1401
4.91M
}
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
76.8k
void DeleteBitmap::remove(const BitmapKey& start, const BitmapKey& end) {
1412
76.8k
    std::lock_guard l(lock);
1413
92.4k
    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
46.8k
            break;
1417
46.8k
        }
1418
15.6k
        it = delete_bitmap.erase(it);
1419
15.6k
    }
1420
76.8k
}
1421
1422
872
void DeleteBitmap::remove(const std::vector<std::tuple<BitmapKey, BitmapKey>>& key_ranges) {
1423
872
    std::lock_guard l(lock);
1424
872
    for (auto& [start, end] : key_ranges) {
1425
1.75k
        for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end();) {
1426
1.75k
            auto& [k, _] = *it;
1427
1.75k
            if (k >= end) {
1428
872
                break;
1429
872
            }
1430
883
            it = delete_bitmap.erase(it);
1431
883
        }
1432
872
    }
1433
872
}
1434
1435
3.71M
bool DeleteBitmap::contains(const BitmapKey& bmk, uint32_t row_id) const {
1436
3.71M
    std::shared_lock l(lock);
1437
3.71M
    auto it = delete_bitmap.find(bmk);
1438
3.71M
    return it != delete_bitmap.end() && it->second.contains(row_id);
1439
3.71M
}
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
146k
uint64_t DeleteBitmap::cardinality() const {
1458
146k
    std::shared_lock l(lock);
1459
146k
    uint64_t res = 0;
1460
1.46M
    for (auto entry : delete_bitmap) {
1461
1.46M
        if (std::get<1>(entry.first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1462
52.3k
            res += entry.second.cardinality();
1463
52.3k
        }
1464
1.46M
    }
1465
146k
    return res;
1466
146k
}
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.70M
                                                       uint32_t row_id) const {
1481
3.70M
    g_contains_agg_with_cache_if_eligible_total << 1;
1482
3.70M
    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.41M
            DeleteBitmapAggCache::instance()->release(handle);
1486
1.41M
        };
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.40M
            cached_version = std::get<2>(bmk);
1493
2.30M
        } else {
1494
            // 2. if not found, try to lookup with cached version
1495
2.30M
            cached_version = _get_rowset_cache_version(bmk);
1496
2.30M
            if (cached_version > 0) {
1497
258
                if (cached_version > std::get<2>(bmk)) {
1498
35
                    cached_version = 0;
1499
223
                } else {
1500
223
                    dbm_handle.reset(DeleteBitmapAggCache::instance()->lookup(agg_cache_key(
1501
223
                            _tablet_id, {std::get<0>(bmk), std::get<1>(bmk), cached_version})));
1502
223
                }
1503
258
            }
1504
2.30M
        }
1505
3.71M
        if (dbm_handle != nullptr) {
1506
1.41M
            const auto& cached_dbm =
1507
1.41M
                    reinterpret_cast<DeleteBitmapAggCache::Value*>(
1508
1.41M
                            DeleteBitmapAggCache::instance()->value(dbm_handle.get()))
1509
1.41M
                            ->bitmap;
1510
1.41M
            if (cached_version == std::get<2>(bmk)) {
1511
1.40M
                g_contains_agg_with_cache_if_eligible_full_hit << 1;
1512
1.40M
            } else {
1513
1.05k
                g_contains_agg_with_cache_if_eligible_partial_hit << 1;
1514
1.05k
            }
1515
1.41M
            if (cached_dbm.contains(row_id)) {
1516
290
                return true;
1517
290
            }
1518
1.41M
            if (cached_version == std::get<2>(bmk)) {
1519
1.41M
                return false;
1520
1.41M
            }
1521
18.4E
            start_version = cached_version + 1;
1522
18.4E
        }
1523
3.71M
    }
1524
2.29M
    DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1525
2.29M
    std::shared_lock l(lock);
1526
2.29M
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1527
1.13M
        auto& [k, bm] = *it;
1528
1.13M
        if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1529
1.13M
            std::get<2>(k) > std::get<2>(bmk)) {
1530
1.13M
            break;
1531
1.13M
        }
1532
453
        if (bm.contains(row_id)) {
1533
20
            return true;
1534
20
        }
1535
453
    }
1536
2.29M
    return false;
1537
2.29M
}
1538
1539
22
void DeleteBitmap::remove_sentinel_marks() {
1540
22
    std::lock_guard l(lock);
1541
808
    for (auto it = delete_bitmap.begin(), end = delete_bitmap.end(); it != end;) {
1542
786
        if (std::get<1>(it->first) == DeleteBitmap::INVALID_SEGMENT_ID) {
1543
775
            it = delete_bitmap.erase(it);
1544
775
        } else {
1545
11
            ++it;
1546
11
        }
1547
786
    }
1548
22
}
1549
1550
9.12k
int DeleteBitmap::set(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1551
9.12k
    std::lock_guard l(lock);
1552
9.12k
    auto [_, inserted] = delete_bitmap.insert_or_assign(bmk, segment_delete_bitmap);
1553
9.12k
    return inserted;
1554
9.12k
}
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.8k
                          DeleteBitmap* subset_rowset_map) const {
1573
64.8k
    DCHECK(start < end);
1574
64.8k
    std::shared_lock l(lock);
1575
72.0k
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1576
17.7k
        auto& [k, bm] = *it;
1577
17.7k
        if (k >= end) {
1578
10.5k
            break;
1579
10.5k
        }
1580
7.22k
        subset_rowset_map->set(k, bm);
1581
7.22k
    }
1582
64.8k
}
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
876
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1634
587
        auto& [k, bm] = *it;
1635
587
        if (k >= end) {
1636
431
            break;
1637
431
        }
1638
156
        count++;
1639
156
    }
1640
720
    return count;
1641
720
}
1642
1643
18.0k
void DeleteBitmap::merge(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1644
18.0k
    std::lock_guard l(lock);
1645
18.0k
    auto [iter, succ] = delete_bitmap.emplace(bmk, segment_delete_bitmap);
1646
18.0k
    if (!succ) {
1647
0
        iter->second |= segment_delete_bitmap;
1648
0
    }
1649
18.0k
}
1650
1651
49.2k
void DeleteBitmap::merge(const DeleteBitmap& other) {
1652
49.2k
    std::lock_guard l(lock);
1653
49.2k
    for (auto& i : other.delete_bitmap) {
1654
1.93k
        auto [j, succ] = this->delete_bitmap.insert(i);
1655
1.93k
        if (!succ) j->second |= i.second;
1656
1.93k
    }
1657
49.2k
}
1658
1659
225k
uint64_t DeleteBitmap::get_delete_bitmap_count() {
1660
225k
    std::shared_lock l(lock);
1661
225k
    uint64_t count = 0;
1662
851k
    for (auto it = delete_bitmap.begin(); it != delete_bitmap.end(); it++) {
1663
625k
        if (std::get<1>(it->first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1664
49.3k
            count++;
1665
49.3k
        }
1666
625k
    }
1667
225k
    return count;
1668
225k
}
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
40
void DeleteBitmap::clear_rowset_cache_version() {
1702
40
    std::lock_guard l(_rowset_cache_version_lock);
1703
40
    _rowset_cache_version.clear();
1704
40
    VLOG_DEBUG << "clear agg cache version for tablet=" << _tablet_id;
1705
40
}
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.41M
DeleteBitmap::Version DeleteBitmap::_get_rowset_cache_version(const BitmapKey& bmk) const {
1717
2.41M
    std::shared_lock l(_rowset_cache_version_lock);
1718
2.41M
    if (auto it = _rowset_cache_version.find(std::get<0>(bmk)); it != _rowset_cache_version.end()) {
1719
14.2k
        auto& segment_cache_version = it->second;
1720
14.2k
        if (auto it1 = segment_cache_version.find(std::get<1>(bmk));
1721
14.2k
            it1 != segment_cache_version.end()) {
1722
14.1k
            return it1->second;
1723
14.1k
        }
1724
14.2k
    }
1725
2.39M
    return 0;
1726
2.41M
}
1727
1728
2
DeleteBitmap DeleteBitmap::agg_cache_snapshot() {
1729
2
    return DeleteBitmapAggCache::instance()->snapshot(_tablet_id);
1730
2
}
1731
1732
568k
void DeleteBitmap::set_tablet_id(int64_t tablet_id) {
1733
568k
    _tablet_id = tablet_id;
1734
568k
}
1735
1736
1.94M
std::shared_ptr<roaring::Roaring> DeleteBitmap::get_agg(const BitmapKey& bmk) const {
1737
1.94M
    std::string key_str = agg_cache_key(_tablet_id, bmk); // Cache key container
1738
1.94M
    CacheKey key(key_str);
1739
1.94M
    Cache::Handle* handle = DeleteBitmapAggCache::instance()->lookup(key);
1740
1741
1.94M
    DeleteBitmapAggCache::Value* val =
1742
1.94M
            handle == nullptr ? nullptr
1743
1.94M
                              : 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.94M
    if (val == nullptr) { // Renew if needed, put a new Value to cache
1748
107k
        val = new DeleteBitmapAggCache::Value();
1749
107k
        Version start_version =
1750
107k
                config::enable_mow_get_agg_by_cache ? _get_rowset_cache_version(bmk) : 0;
1751
107k
        if (start_version > 0) {
1752
13.9k
            Cache::Handle* handle2 = DeleteBitmapAggCache::instance()->lookup(
1753
13.9k
                    agg_cache_key(_tablet_id, {std::get<0>(bmk), std::get<1>(bmk), start_version}));
1754
1755
13.9k
            DBUG_EXECUTE_IF("DeleteBitmap::get_agg.cache_miss", {
1756
13.9k
                if (handle2 != nullptr) {
1757
13.9k
                    auto p = dp->param("percent", 0.3);
1758
13.9k
                    std::mt19937 gen {std::random_device {}()};
1759
13.9k
                    std::bernoulli_distribution inject_fault {p};
1760
13.9k
                    if (inject_fault(gen)) {
1761
13.9k
                        LOG_INFO("injection DeleteBitmap::get_agg.cache_miss, tablet_id={}",
1762
13.9k
                                 _tablet_id);
1763
13.9k
                        handle2 = nullptr;
1764
13.9k
                    }
1765
13.9k
                }
1766
13.9k
            });
1767
13.9k
            if (handle2 == nullptr || start_version > std::get<2>(bmk)) {
1768
182
                start_version = 0;
1769
13.7k
            } else {
1770
13.7k
                val->bitmap |= reinterpret_cast<DeleteBitmapAggCache::Value*>(
1771
13.7k
                                       DeleteBitmapAggCache::instance()->value(handle2))
1772
13.7k
                                       ->bitmap;
1773
13.7k
                VLOG_DEBUG << "get agg cache version=" << start_version
1774
31
                           << " for tablet=" << _tablet_id
1775
31
                           << ", rowset=" << std::get<0>(bmk).to_string()
1776
31
                           << ", segment=" << std::get<1>(bmk);
1777
13.7k
                start_version += 1;
1778
13.7k
            }
1779
13.9k
            if (handle2 != nullptr) {
1780
13.8k
                DeleteBitmapAggCache::instance()->release(handle2);
1781
13.8k
            }
1782
13.9k
        }
1783
107k
        {
1784
107k
            std::shared_lock l(lock);
1785
107k
            DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1786
115k
            for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1787
26.2k
                auto& [k, bm] = *it;
1788
26.2k
                if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1789
26.2k
                    std::get<2>(k) > std::get<2>(bmk)) {
1790
18.1k
                    break;
1791
18.1k
                }
1792
8.10k
                val->bitmap |= bm;
1793
8.10k
            }
1794
107k
        }
1795
107k
        size_t charge = val->bitmap.getSizeInBytes() + sizeof(DeleteBitmapAggCache::Value);
1796
107k
        handle = DeleteBitmapAggCache::instance()->insert(key, val, charge, charge,
1797
107k
                                                          CachePriority::NORMAL);
1798
107k
        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
6
                       << " for tablet=" << _tablet_id
1804
6
                       << ", rowset=" << std::get<0>(bmk).to_string()
1805
6
                       << ", segment=" << std::get<1>(bmk);
1806
20.2k
        }
1807
107k
        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
107k
    }
1821
1822
    // It is natural for the cache to reclaim the underlying memory
1823
1.94M
    return std::shared_ptr<roaring::Roaring>(
1824
1.94M
            &val->bitmap, [handle](...) { DeleteBitmapAggCache::instance()->release(handle); });
1825
1.94M
}
1826
1827
std::shared_ptr<roaring::Roaring> DeleteBitmap::get_agg_without_cache(
1828
6.16k
        const BitmapKey& bmk, const int64_t start_version) const {
1829
6.16k
    std::shared_ptr<roaring::Roaring> bitmap = std::make_shared<roaring::Roaring>();
1830
6.16k
    std::shared_lock l(lock);
1831
6.16k
    DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1832
31.2k
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1833
29.6k
        auto& [k, bm] = *it;
1834
29.6k
        if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1835
29.6k
            std::get<2>(k) > std::get<2>(bmk)) {
1836
4.58k
            break;
1837
4.58k
        }
1838
25.0k
        *bitmap |= bm;
1839
25.0k
    }
1840
6.16k
    return bitmap;
1841
6.16k
}
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
0
std::string tablet_state_name(TabletState state) {
1860
0
    switch (state) {
1861
0
    case TABLET_NOTREADY:
1862
0
        return "TABLET_NOTREADY";
1863
1864
0
    case TABLET_RUNNING:
1865
0
        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
0
    }
1879
0
}
1880
1881
} // namespace doris