Coverage Report

Created: 2026-08-13 13:23

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