Coverage Report

Created: 2026-08-14 23:14

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
236
        const unordered_map<uint32_t, uint32_t>& col_ordinal_to_unique_id) {
89
236
    std::optional<TBinlogConfig> binlog_config;
90
236
    if (request.__isset.binlog_config) {
91
23
        binlog_config = request.binlog_config;
92
23
    }
93
236
    TInvertedIndexFileStorageFormat::type inverted_index_file_storage_format =
94
236
            request.inverted_index_file_storage_format;
95
96
    // We will discard this format. Don't make any further changes here.
97
236
    if (request.__isset.inverted_index_storage_format) {
98
236
        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
236
        default:
106
236
            break;
107
236
        }
108
236
    }
109
    // Decide storage format for this tablet. DEFAULT / not-set fall back to V2 on BE side.
110
236
    TStorageFormat::type storage_format =
111
236
            request.__isset.storage_format ? request.storage_format : TStorageFormat::V2;
112
236
    return std::make_shared<TabletMeta>(
113
236
            request.table_id, request.partition_id, request.tablet_id, request.replica_id,
114
236
            request.tablet_schema.schema_hash, shard_id, request.tablet_schema, next_unique_id,
115
236
            col_ordinal_to_unique_id, tablet_uid,
116
236
            request.__isset.tablet_type ? request.tablet_type : TTabletType::TABLET_TYPE_DISK,
117
236
            request.__isset.compression_type ? request.compression_type : TCompressionType::LZ4F,
118
236
            request.__isset.storage_policy_id ? request.storage_policy_id : -1,
119
236
            request.__isset.enable_unique_key_merge_on_write
120
236
                    ? request.enable_unique_key_merge_on_write
121
236
                    : false,
122
236
            std::move(binlog_config), request.compaction_policy,
123
236
            request.time_series_compaction_goal_size_mbytes,
124
236
            request.time_series_compaction_file_count_threshold,
125
236
            request.time_series_compaction_time_threshold_seconds,
126
236
            request.time_series_compaction_empty_rowsets_threshold,
127
236
            request.time_series_compaction_level_threshold, inverted_index_file_storage_format,
128
236
            request.tde_algorithm, storage_format,
129
236
            request.__isset.vertical_compaction_num_columns_per_group
130
236
                    ? request.vertical_compaction_num_columns_per_group
131
236
                    : 5,
132
236
            request.__isset.tablet_role ? request.tablet_role : TTabletRole::TABLET_ROLE_DATA);
133
236
}
134
135
1.39k
TabletMeta::~TabletMeta() {
136
1.39k
    if (_handle) {
137
967
        TabletSchemaCache::instance()->release(_handle);
138
967
    }
139
1.39k
}
140
141
TabletMeta::TabletMeta()
142
419
        : _tablet_uid(0, 0),
143
419
          _schema(new TabletSchema),
144
419
          _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
665
        : _tablet_uid(0, 0),
165
665
          _schema(new TabletSchema),
166
665
          _delete_bitmap(new DeleteBitmap(tablet_id)),
167
665
          _storage_format(storage_format) {
168
665
    TabletMetaPB tablet_meta_pb;
169
665
    tablet_meta_pb.set_table_id(table_id);
170
665
    tablet_meta_pb.set_partition_id(partition_id);
171
665
    tablet_meta_pb.set_tablet_id(tablet_id);
172
665
    tablet_meta_pb.set_replica_id(replica_id);
173
665
    tablet_meta_pb.set_schema_hash(schema_hash);
174
665
    tablet_meta_pb.set_shard_id(shard_id);
175
    // Persist the creation time, but it is not used
176
665
    tablet_meta_pb.set_creation_time(time(nullptr));
177
665
    tablet_meta_pb.set_cumulative_layer_point(-1);
178
665
    tablet_meta_pb.set_tablet_state(PB_RUNNING);
179
665
    *(tablet_meta_pb.mutable_tablet_uid()) = tablet_uid.to_proto();
180
665
    tablet_meta_pb.set_tablet_type(tabletType == TTabletType::TABLET_TYPE_DISK
181
665
                                           ? TabletTypePB::TABLET_TYPE_DISK
182
665
                                           : TabletTypePB::TABLET_TYPE_MEMORY);
183
665
    tablet_meta_pb.set_enable_unique_key_merge_on_write(enable_unique_key_merge_on_write);
184
665
    tablet_meta_pb.set_storage_policy_id(storage_policy_id);
185
665
    tablet_meta_pb.set_compaction_policy(compaction_policy);
186
665
    tablet_meta_pb.set_time_series_compaction_goal_size_mbytes(
187
665
            time_series_compaction_goal_size_mbytes);
188
665
    tablet_meta_pb.set_time_series_compaction_file_count_threshold(
189
665
            time_series_compaction_file_count_threshold);
190
665
    tablet_meta_pb.set_time_series_compaction_time_threshold_seconds(
191
665
            time_series_compaction_time_threshold_seconds);
192
665
    tablet_meta_pb.set_time_series_compaction_empty_rowsets_threshold(
193
665
            time_series_compaction_empty_rowsets_threshold);
194
665
    tablet_meta_pb.set_time_series_compaction_level_threshold(
195
665
            time_series_compaction_level_threshold);
196
665
    tablet_meta_pb.set_vertical_compaction_num_columns_per_group(
197
665
            vertical_compaction_num_columns_per_group);
198
665
    tablet_meta_pb.set_tablet_role(tablet_role == TTabletRole::TABLET_ROLE_ROW_BINLOG
199
665
                                           ? TabletRolePB::TABLET_ROLE_ROW_BINLOG
200
665
                                           : TabletRolePB::TABLET_ROLE_DATA);
201
665
    SchemaCreateOptions schema_create_options_for_data = {
202
665
            .col_ordinal_to_unique_id = col_ordinal_to_unique_id,
203
665
            .compression_type = compression_type,
204
665
            .inverted_index_file_storage_format = inverted_index_file_storage_format,
205
665
            .next_unique_id = next_unique_id};
206
665
    TabletSchemaPB* schema_pb_for_data = tablet_meta_pb.mutable_schema();
207
665
    init_schema_from_thrift(tablet_schema, schema_create_options_for_data, schema_pb_for_data);
208
209
665
    tablet_meta_pb.set_in_restore_mode(false);
210
211
665
    if (binlog_config.has_value()) {
212
23
        BinlogConfig tmp_binlog_config;
213
23
        tmp_binlog_config = binlog_config.value();
214
23
        tmp_binlog_config.to_pb(tablet_meta_pb.mutable_binlog_config());
215
23
    }
216
217
665
    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
665
    default:
225
665
        tablet_meta_pb.set_encryption_algorithm(EncryptionAlgorithmPB::PLAINTEXT);
226
665
    }
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
665
    switch (_storage_format) {
232
665
    case TStorageFormat::V2:
233
665
    case TStorageFormat::DEFAULT:
234
665
    case TStorageFormat::V1:
235
665
        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
665
    }
243
244
665
    init_from_pb(tablet_meta_pb);
245
665
}
246
247
TabletMeta::TabletMeta(const TabletMeta& b)
248
133
        : MetadataAdder(b),
249
133
          _table_id(b._table_id),
250
133
          _index_id(b._index_id),
251
133
          _partition_id(b._partition_id),
252
133
          _tablet_id(b._tablet_id),
253
133
          _replica_id(b._replica_id),
254
133
          _schema_hash(b._schema_hash),
255
133
          _shard_id(b._shard_id),
256
133
          _creation_time(b._creation_time),
257
133
          _cumulative_layer_point(b._cumulative_layer_point),
258
133
          _tablet_uid(b._tablet_uid),
259
133
          _tablet_type(b._tablet_type),
260
133
          _tablet_state(b._tablet_state),
261
133
          _schema(b._schema),
262
133
          _rs_metas(b._rs_metas),
263
133
          _stale_rs_metas(b._stale_rs_metas),
264
133
          _in_restore_mode(b._in_restore_mode),
265
133
          _preferred_rowset_type(b._preferred_rowset_type),
266
133
          _storage_policy_id(b._storage_policy_id),
267
133
          _cooldown_meta_id(b._cooldown_meta_id),
268
133
          _enable_unique_key_merge_on_write(b._enable_unique_key_merge_on_write),
269
133
          _delete_bitmap(b._delete_bitmap),
270
133
          _binlog_config(b._binlog_config),
271
133
          _tablet_role(b._tablet_role),
272
133
          _compaction_policy(b._compaction_policy),
273
133
          _time_series_compaction_goal_size_mbytes(b._time_series_compaction_goal_size_mbytes),
274
          _time_series_compaction_file_count_threshold(
275
133
                  b._time_series_compaction_file_count_threshold),
276
          _time_series_compaction_time_threshold_seconds(
277
133
                  b._time_series_compaction_time_threshold_seconds),
278
          _time_series_compaction_empty_rowsets_threshold(
279
133
                  b._time_series_compaction_empty_rowsets_threshold),
280
133
          _time_series_compaction_level_threshold(b._time_series_compaction_level_threshold),
281
          _vertical_compaction_num_columns_per_group(
282
133
                  b._vertical_compaction_num_columns_per_group) {};
283
284
void TabletMeta::init_column_from_tcolumn(uint32_t unique_id, const TColumn& tcolumn,
285
2.11k
                                          ColumnPB* column) {
286
2.11k
    column->set_unique_id(unique_id);
287
2.11k
    column->set_name(tcolumn.column_name);
288
2.11k
    column->set_is_auto_increment(tcolumn.is_auto_increment);
289
2.11k
    if (tcolumn.__isset.is_on_update_current_timestamp) {
290
2.11k
        column->set_is_on_update_current_timestamp(tcolumn.is_on_update_current_timestamp);
291
2.11k
    }
292
2.11k
    string data_type;
293
2.11k
    EnumToString(TPrimitiveType, tcolumn.column_type.type, data_type);
294
2.11k
    column->set_type(data_type);
295
296
2.11k
    uint32_t length = TabletColumn::get_field_length_by_type(tcolumn.column_type.type,
297
2.11k
                                                             tcolumn.column_type.len);
298
2.11k
    column->set_length(length);
299
2.11k
    column->set_index_length(length);
300
2.11k
    column->set_precision(tcolumn.column_type.precision);
301
2.11k
    column->set_frac(tcolumn.column_type.scale);
302
303
2.11k
    if (tcolumn.__isset.result_is_nullable) {
304
0
        column->set_result_is_nullable(tcolumn.result_is_nullable);
305
0
    }
306
307
2.11k
    if (tcolumn.__isset.be_exec_version) {
308
2.11k
        column->set_be_exec_version(tcolumn.be_exec_version);
309
2.11k
    }
310
311
2.11k
    if (tcolumn.column_type.type == TPrimitiveType::VARCHAR ||
312
2.11k
        tcolumn.column_type.type == TPrimitiveType::STRING) {
313
108
        if (!tcolumn.column_type.__isset.index_len) {
314
108
            column->set_index_length(10);
315
108
        } else {
316
0
            column->set_index_length(tcolumn.column_type.index_len);
317
0
        }
318
108
    }
319
2.11k
    if (!tcolumn.is_key) {
320
1.08k
        column->set_is_key(false);
321
1.08k
        if (tcolumn.__isset.aggregation) {
322
0
            column->set_aggregation(tcolumn.aggregation);
323
1.08k
        } else {
324
1.08k
            string aggregation_type;
325
1.08k
            EnumToString(TAggregationType, tcolumn.aggregation_type, aggregation_type);
326
1.08k
            column->set_aggregation(aggregation_type);
327
1.08k
        }
328
1.08k
    } else {
329
1.03k
        column->set_is_key(true);
330
1.03k
        column->set_aggregation("NONE");
331
1.03k
    }
332
2.11k
    column->set_is_nullable(tcolumn.is_allow_null);
333
2.11k
    if (tcolumn.__isset.default_value) {
334
11
        column->set_default_value(tcolumn.default_value);
335
11
    }
336
2.11k
    if (tcolumn.__isset.is_bloom_filter_column) {
337
1
        column->set_is_bf_column(tcolumn.is_bloom_filter_column);
338
1
    }
339
2.11k
    if (tcolumn.__isset.visible) {
340
2.11k
        column->set_visible(tcolumn.visible);
341
2.11k
    }
342
2.11k
    for (size_t i = 0; i < tcolumn.children_column.size(); i++) {
343
0
        ColumnPB* children_column = column->add_children_columns();
344
0
        init_column_from_tcolumn(tcolumn.children_column[i].col_unique_id,
345
0
                                 tcolumn.children_column[i], children_column);
346
0
    }
347
2.11k
    if (tcolumn.column_type.__isset.variant_max_subcolumns_count) {
348
2.11k
        column->set_variant_max_subcolumns_count(tcolumn.column_type.variant_max_subcolumns_count);
349
2.11k
    }
350
2.11k
    if (tcolumn.__isset.pattern_type) {
351
1
        switch (tcolumn.pattern_type) {
352
0
        case TPatternType::MATCH_NAME:
353
0
            column->set_pattern_type(PatternTypePB::MATCH_NAME);
354
0
            break;
355
1
        case TPatternType::MATCH_NAME_GLOB:
356
1
            column->set_pattern_type(PatternTypePB::MATCH_NAME_GLOB);
357
1
        }
358
1
    }
359
2.11k
    if (tcolumn.__isset.variant_enable_typed_paths_to_sparse) {
360
2.11k
        column->set_variant_enable_typed_paths_to_sparse(
361
2.11k
                tcolumn.variant_enable_typed_paths_to_sparse);
362
2.11k
    }
363
2.11k
    if (tcolumn.__isset.variant_max_sparse_column_statistics_size) {
364
2.11k
        column->set_variant_max_sparse_column_statistics_size(
365
2.11k
                tcolumn.variant_max_sparse_column_statistics_size);
366
2.11k
    }
367
2.11k
    if (tcolumn.__isset.variant_sparse_hash_shard_count) {
368
0
        column->set_variant_sparse_hash_shard_count(tcolumn.variant_sparse_hash_shard_count);
369
0
    }
370
2.11k
    if (tcolumn.column_type.__isset.variant_enable_doc_mode) {
371
2.11k
        column->set_variant_enable_doc_mode(tcolumn.column_type.variant_enable_doc_mode);
372
2.11k
    }
373
2.11k
    if (tcolumn.__isset.variant_doc_materialization_min_rows) {
374
0
        column->set_variant_doc_materialization_min_rows(
375
0
                tcolumn.variant_doc_materialization_min_rows);
376
0
    }
377
2.11k
    if (tcolumn.__isset.variant_doc_hash_shard_count) {
378
0
        column->set_variant_doc_hash_shard_count(tcolumn.variant_doc_hash_shard_count);
379
0
    }
380
2.11k
    if (tcolumn.__isset.variant_enable_nested_group) {
381
0
        column->set_variant_enable_nested_group(tcolumn.variant_enable_nested_group);
382
0
    }
383
2.11k
}
384
385
void TabletMeta::init_schema_from_thrift(const TTabletSchema& tablet_schema,
386
                                         const SchemaCreateOptions& schema_create_options,
387
665
                                         TabletSchemaPB* tablet_schema_pb) {
388
665
    const std::unordered_map<uint32_t, uint32_t>& col_ordinal_to_unique_id =
389
665
            schema_create_options.col_ordinal_to_unique_id;
390
665
    TCompressionType::type compression_type = schema_create_options.compression_type;
391
665
    TInvertedIndexFileStorageFormat::type inverted_index_file_storage_format =
392
665
            schema_create_options.inverted_index_file_storage_format;
393
665
    uint32_t next_unique_id = schema_create_options.next_unique_id;
394
395
665
    tablet_schema_pb->set_num_short_key_columns(tablet_schema.short_key_column_count);
396
665
    tablet_schema_pb->set_num_rows_per_row_block(config::default_num_rows_per_column_file_block);
397
665
    tablet_schema_pb->set_sequence_col_idx(tablet_schema.sequence_col_idx);
398
665
    if (tablet_schema.__isset.binlog_tso_idx) {
399
665
        tablet_schema_pb->set_binlog_tso_col_idx(tablet_schema.binlog_tso_idx);
400
665
    }
401
665
    if (tablet_schema.__isset.binlog_lsn_idx) {
402
665
        tablet_schema_pb->set_binlog_lsn_col_idx(tablet_schema.binlog_lsn_idx);
403
665
    }
404
665
    if (tablet_schema.__isset.binlog_op_idx) {
405
665
        tablet_schema_pb->set_binlog_op_col_idx(tablet_schema.binlog_op_idx);
406
665
    }
407
665
    auto p_seq_map = tablet_schema_pb->mutable_seq_map(); // ColumnGroupsPB
408
665
    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
665
    switch (tablet_schema.keys_type) {
418
69
    case TKeysType::DUP_KEYS:
419
69
        tablet_schema_pb->set_keys_type(KeysType::DUP_KEYS);
420
69
        break;
421
233
    case TKeysType::UNIQUE_KEYS:
422
233
        tablet_schema_pb->set_keys_type(KeysType::UNIQUE_KEYS);
423
233
        break;
424
70
    case TKeysType::AGG_KEYS:
425
70
        tablet_schema_pb->set_keys_type(KeysType::AGG_KEYS);
426
70
        break;
427
293
    default:
428
293
        LOG(WARNING) << "unknown tablet keys type";
429
293
        break;
430
665
    }
431
432
    // compress_kind used to compress segment files
433
665
    tablet_schema_pb->set_compress_kind(COMPRESS_LZ4);
434
435
    // compression_type used to compress segment page
436
665
    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
665
    case TCompressionType::LZ4F:
447
665
        tablet_schema_pb->set_compression_type(segment_v2::LZ4F);
448
665
        break;
449
0
    case TCompressionType::ZLIB:
450
0
        tablet_schema_pb->set_compression_type(segment_v2::ZLIB);
451
0
        break;
452
0
    case TCompressionType::ZSTD:
453
0
        tablet_schema_pb->set_compression_type(segment_v2::ZSTD);
454
0
        break;
455
0
    default:
456
0
        tablet_schema_pb->set_compression_type(segment_v2::LZ4F);
457
0
        break;
458
665
    }
459
460
665
    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
665
    case TInvertedIndexFileStorageFormat::V2:
465
665
        tablet_schema_pb->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V2);
466
665
        break;
467
0
    case TInvertedIndexFileStorageFormat::V3:
468
0
        tablet_schema_pb->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V3);
469
0
        break;
470
0
    default:
471
0
        tablet_schema_pb->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V3);
472
0
        break;
473
665
    }
474
475
665
    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
665
    default:
480
665
        tablet_schema_pb->set_sort_type(SortType::LEXICAL);
481
665
    }
482
665
    tablet_schema_pb->set_sort_col_num(tablet_schema.sort_col_num);
483
665
    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
665
    uint32_t col_ordinal = 0;
489
665
    bool has_bf_columns = false;
490
2.08k
    for (TColumn tcolumn : tablet_schema.columns) {
491
2.08k
        ColumnPB* column = tablet_schema_pb->add_column();
492
2.08k
        uint32_t unique_id = -1;
493
2.08k
        if (tcolumn.col_unique_id >= 0) {
494
11
            unique_id = tcolumn.col_unique_id;
495
2.06k
        } else {
496
2.06k
            unique_id = col_ordinal_to_unique_id.at(col_ordinal);
497
2.06k
        }
498
2.08k
        init_column_from_tcolumn(unique_id, tcolumn, column);
499
500
2.08k
        col_ordinal++;
501
502
2.08k
        if (column->is_bf_column()) {
503
0
            has_bf_columns = true;
504
0
        }
505
506
2.08k
        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
2.08k
    }
519
520
    // copy index meta
521
665
    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
665
    tablet_schema_pb->set_next_column_unique_id(next_unique_id);
563
665
    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
665
    if (tablet_schema.__isset.is_in_memory) {
568
0
        tablet_schema_pb->set_is_in_memory(tablet_schema.is_in_memory);
569
0
    }
570
571
665
    if (tablet_schema.__isset.disable_auto_compaction) {
572
10
        tablet_schema_pb->set_disable_auto_compaction(tablet_schema.disable_auto_compaction);
573
10
    }
574
575
    // Deprecated legacy flatten-nested switch. Distinct from variant_enable_nested_group.
576
665
    if (tablet_schema.__isset.variant_enable_flatten_nested) {
577
665
        tablet_schema_pb->set_enable_variant_flatten_nested(
578
665
                tablet_schema.variant_enable_flatten_nested);
579
665
    }
580
581
665
    if (tablet_schema.__isset.delete_sign_idx) {
582
665
        tablet_schema_pb->set_delete_sign_idx(tablet_schema.delete_sign_idx);
583
665
    }
584
665
    if (tablet_schema.__isset.commit_tso_col_idx) {
585
665
        tablet_schema_pb->set_commit_tso_col_idx(tablet_schema.commit_tso_col_idx);
586
665
    }
587
665
    if (tablet_schema.__isset.store_row_column) {
588
665
        tablet_schema_pb->set_store_row_column(tablet_schema.store_row_column);
589
665
    }
590
665
    if (tablet_schema.__isset.row_store_page_size) {
591
665
        tablet_schema_pb->set_row_store_page_size(tablet_schema.row_store_page_size);
592
665
    }
593
665
    if (tablet_schema.__isset.storage_page_size) {
594
665
        tablet_schema_pb->set_storage_page_size(tablet_schema.storage_page_size);
595
665
    }
596
665
    if (tablet_schema.__isset.storage_dict_page_size) {
597
665
        tablet_schema_pb->set_storage_dict_page_size(tablet_schema.storage_dict_page_size);
598
665
    }
599
665
    if (tablet_schema.__isset.skip_write_index_on_load) {
600
665
        tablet_schema_pb->set_skip_write_index_on_load(tablet_schema.skip_write_index_on_load);
601
665
    }
602
665
    if (tablet_schema.__isset.row_store_col_cids) {
603
0
        tablet_schema_pb->mutable_row_store_column_unique_ids()->Add(
604
0
                tablet_schema.row_store_col_cids.begin(), tablet_schema.row_store_col_cids.end());
605
0
    }
606
665
}
607
608
0
void TabletMeta::remove_rowset_delete_bitmap(const RowsetId& rowset_id, const Version& version) {
609
0
    if (_enable_unique_key_merge_on_write) {
610
0
        delete_bitmap().remove({rowset_id, 0, 0}, {rowset_id, UINT32_MAX, 0});
611
0
        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
0
        size_t rowset_cache_version_size = delete_bitmap().remove_rowset_cache_version(rowset_id);
616
0
        _check_mow_rowset_cache_version_size(rowset_cache_version_size);
617
0
    }
618
0
}
619
620
4
Status TabletMeta::create_from_file(const string& file_path) {
621
4
    TabletMetaPB tablet_meta_pb;
622
4
    RETURN_IF_ERROR(load_from_file(file_path, &tablet_meta_pb));
623
4
    init_from_pb(tablet_meta_pb);
624
4
    return Status::OK();
625
4
}
626
627
12
Status TabletMeta::load_from_file(const string& file_path, TabletMetaPB* tablet_meta_pb) {
628
12
    FileHeader<TabletMetaPB> file_header(file_path);
629
    // In file_header.deserialize(), it validates file length, signature, checksum of protobuf.
630
12
    RETURN_IF_ERROR(file_header.deserialize());
631
12
    try {
632
12
        tablet_meta_pb->CopyFrom(file_header.message());
633
12
    } 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
12
    return Status::OK();
640
12
}
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
3
                                                   int64_t tablet_id) {
661
3
    std::stringstream header_name_stream;
662
3
    header_name_stream << schema_hash_path << "/" << tablet_id << ".hdr";
663
3
    return header_name_stream.str();
664
3
}
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
131
Status TabletMeta::save(const string& file_path) {
681
131
    TabletMetaPB tablet_meta_pb;
682
131
    to_meta_pb(&tablet_meta_pb, false);
683
131
    return TabletMeta::save(file_path, tablet_meta_pb);
684
131
}
685
686
137
Status TabletMeta::save(const string& file_path, const TabletMetaPB& tablet_meta_pb) {
687
137
    DCHECK(!file_path.empty());
688
137
    FileHeader<TabletMetaPB> file_header(file_path);
689
137
    try {
690
137
        file_header.mutable_message()->CopyFrom(tablet_meta_pb);
691
137
    } 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
137
    RETURN_IF_ERROR(file_header.prepare());
697
137
    RETURN_IF_ERROR(file_header.serialize());
698
137
    return Status::OK();
699
137
}
700
701
442
Status TabletMeta::save_meta(DataDir* data_dir) {
702
442
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
703
442
    return _save_meta(data_dir);
704
442
}
705
706
442
Status TabletMeta::_save_meta(DataDir* data_dir) {
707
    // check if tablet uid is valid
708
442
    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
442
    string meta_binary;
713
714
442
    auto t1 = MonotonicMicros();
715
442
    serialize(&meta_binary);
716
442
    auto t2 = MonotonicMicros();
717
442
    Status status = TabletMetaManager::save(data_dir, tablet_id(), schema_hash(), meta_binary);
718
442
    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
442
    auto t3 = MonotonicMicros();
723
442
    auto cost = t3 - t1;
724
442
    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
442
    return status;
730
442
}
731
732
447
void TabletMeta::serialize(string* meta_binary) {
733
447
    TabletMetaPB tablet_meta_pb;
734
447
    to_meta_pb(&tablet_meta_pb, false);
735
447
    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
447
    DBUG_EXECUTE_IF("TabletMeta::serialize::zero_partition_id", {
740
447
        long partition_id = tablet_meta_pb.partition_id();
741
447
        tablet_meta_pb.set_partition_id(0);
742
447
        LOG(WARNING) << "set debug point TabletMeta::serialize::zero_partition_id old="
743
447
                     << partition_id << " new=" << tablet_meta_pb.DebugString();
744
447
    });
745
447
    bool serialize_success = tablet_meta_pb.SerializeToString(meta_binary);
746
447
    if (!_rs_metas.empty() || !_stale_rs_metas.empty()) {
747
447
        _avg_rs_meta_serialize_size =
748
447
                meta_binary->length() / (_rs_metas.size() + _stale_rs_metas.size());
749
447
        if (meta_binary->length() > config::tablet_meta_serialize_size_limit ||
750
447
            !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
447
    }
764
765
447
    if (!serialize_success) {
766
0
        LOG(FATAL) << "failed to serialize meta " << tablet_id();
767
0
    }
768
447
}
769
770
263
Status TabletMeta::deserialize(std::string_view meta_binary) {
771
263
    TabletMetaPB tablet_meta_pb;
772
263
    bool parsed = tablet_meta_pb.ParseFromArray(meta_binary.data(),
773
263
                                                static_cast<int32_t>(meta_binary.size()));
774
263
    if (!parsed) {
775
0
        return Status::Error<INIT_FAILED>("parse tablet meta failed");
776
0
    }
777
263
    init_from_pb(tablet_meta_pb);
778
263
    return Status::OK();
779
263
}
780
781
971
void TabletMeta::init_from_pb(const TabletMetaPB& tablet_meta_pb) {
782
971
    _table_id = tablet_meta_pb.table_id();
783
971
    _index_id = tablet_meta_pb.index_id();
784
971
    _partition_id = tablet_meta_pb.partition_id();
785
971
    _tablet_id = tablet_meta_pb.tablet_id();
786
971
    _replica_id = tablet_meta_pb.replica_id();
787
971
    _schema_hash = tablet_meta_pb.schema_hash();
788
971
    _shard_id = tablet_meta_pb.shard_id();
789
971
    _creation_time = tablet_meta_pb.creation_time();
790
971
    _cumulative_layer_point = tablet_meta_pb.cumulative_layer_point();
791
971
    _tablet_uid = TabletUid(tablet_meta_pb.tablet_uid());
792
971
    _ttl_seconds = tablet_meta_pb.ttl_seconds();
793
971
    if (tablet_meta_pb.has_tablet_type()) {
794
942
        _tablet_type = tablet_meta_pb.tablet_type();
795
942
    } else {
796
29
        _tablet_type = TabletTypePB::TABLET_TYPE_DISK;
797
29
    }
798
799
    // init _tablet_state
800
971
    switch (tablet_meta_pb.tablet_state()) {
801
32
    case PB_NOTREADY:
802
32
        _tablet_state = TabletState::TABLET_NOTREADY;
803
32
        break;
804
813
    case PB_RUNNING:
805
813
        _tablet_state = TabletState::TABLET_RUNNING;
806
813
        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
126
    case PB_SHUTDOWN:
814
126
        _tablet_state = TabletState::TABLET_SHUTDOWN;
815
126
        break;
816
0
    default:
817
0
        LOG(WARNING) << "tablet has no state. tablet=" << tablet_id()
818
0
                     << ", schema_hash=" << schema_hash();
819
971
    }
820
821
    // init _schema
822
971
    TabletSchemaSPtr schema = std::make_shared<TabletSchema>();
823
971
    schema->init_from_pb(tablet_meta_pb.schema());
824
971
    if (_handle) {
825
4
        TabletSchemaCache::instance()->release(_handle);
826
4
    }
827
971
    auto pair = TabletSchemaCache::instance()->insert(schema->to_key());
828
971
    _handle = pair.first;
829
971
    _schema = pair.second;
830
831
971
    if (tablet_meta_pb.has_enable_unique_key_merge_on_write()) {
832
942
        _enable_unique_key_merge_on_write = tablet_meta_pb.enable_unique_key_merge_on_write();
833
942
        _delete_bitmap->set_tablet_id(_tablet_id);
834
942
    }
835
836
    // init _rs_metas
837
5.54k
    for (auto& it : tablet_meta_pb.rs_metas()) {
838
5.54k
        RowsetMetaSharedPtr rs_meta(new RowsetMeta());
839
5.54k
        rs_meta->init_from_pb(it);
840
5.54k
        _rs_metas.emplace(rs_meta->version(), rs_meta);
841
5.54k
    }
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
971
    if (!config::skip_loading_stale_rowset_meta && !_enable_unique_key_merge_on_write) {
847
909
        for (auto& it : tablet_meta_pb.stale_rs_metas()) {
848
0
            RowsetMetaSharedPtr rs_meta(new RowsetMeta());
849
0
            rs_meta->init_from_pb(it);
850
0
            _stale_rs_metas.emplace(rs_meta->version(), rs_meta);
851
0
        }
852
909
    }
853
854
971
    if (tablet_meta_pb.has_in_restore_mode()) {
855
942
        _in_restore_mode = tablet_meta_pb.in_restore_mode();
856
942
    }
857
858
971
    if (tablet_meta_pb.has_preferred_rowset_type()) {
859
277
        _preferred_rowset_type = tablet_meta_pb.preferred_rowset_type();
860
277
    }
861
862
971
    _storage_policy_id = tablet_meta_pb.storage_policy_id();
863
971
    if (tablet_meta_pb.has_cooldown_meta_id()) {
864
0
        _cooldown_meta_id = tablet_meta_pb.cooldown_meta_id();
865
0
    }
866
867
971
    if (tablet_meta_pb.has_delete_bitmap()) {
868
0
        int rst_ids_size = tablet_meta_pb.delete_bitmap().rowset_ids_size();
869
0
        int seg_ids_size = tablet_meta_pb.delete_bitmap().segment_ids_size();
870
0
        int versions_size = tablet_meta_pb.delete_bitmap().versions_size();
871
0
        int seg_maps_size = tablet_meta_pb.delete_bitmap().segment_delete_bitmaps_size();
872
0
        CHECK(rst_ids_size == seg_ids_size && seg_ids_size == seg_maps_size &&
873
0
              seg_maps_size == versions_size);
874
0
        for (int i = 0; i < rst_ids_size; ++i) {
875
0
            RowsetId rst_id;
876
0
            rst_id.init(tablet_meta_pb.delete_bitmap().rowset_ids(i));
877
0
            auto seg_id = tablet_meta_pb.delete_bitmap().segment_ids(i);
878
0
            auto ver = tablet_meta_pb.delete_bitmap().versions(i);
879
0
            auto bitmap = tablet_meta_pb.delete_bitmap().segment_delete_bitmaps(i).data();
880
0
            delete_bitmap().delete_bitmap[{rst_id, seg_id, ver}] = roaring::Roaring::read(bitmap);
881
0
        }
882
0
    }
883
884
971
    if (tablet_meta_pb.has_binlog_config()) {
885
298
        _binlog_config = tablet_meta_pb.binlog_config();
886
298
    }
887
971
    _tablet_role = tablet_meta_pb.tablet_role();
888
971
    _compaction_policy = tablet_meta_pb.compaction_policy();
889
971
    _time_series_compaction_goal_size_mbytes =
890
971
            tablet_meta_pb.time_series_compaction_goal_size_mbytes();
891
971
    _time_series_compaction_file_count_threshold =
892
971
            tablet_meta_pb.time_series_compaction_file_count_threshold();
893
971
    _time_series_compaction_time_threshold_seconds =
894
971
            tablet_meta_pb.time_series_compaction_time_threshold_seconds();
895
971
    _time_series_compaction_empty_rowsets_threshold =
896
971
            tablet_meta_pb.time_series_compaction_empty_rowsets_threshold();
897
971
    _time_series_compaction_level_threshold =
898
971
            tablet_meta_pb.time_series_compaction_level_threshold();
899
971
    _vertical_compaction_num_columns_per_group =
900
971
            tablet_meta_pb.vertical_compaction_num_columns_per_group();
901
902
971
    if (tablet_meta_pb.has_encryption_algorithm()) {
903
940
        _encryption_algorithm = tablet_meta_pb.encryption_algorithm();
904
940
    }
905
971
}
906
907
593
void TabletMeta::to_meta_pb(TabletMetaPB* tablet_meta_pb, bool cloud_get_rowset_meta) {
908
593
    tablet_meta_pb->set_table_id(table_id());
909
593
    tablet_meta_pb->set_index_id(index_id());
910
593
    tablet_meta_pb->set_partition_id(partition_id());
911
593
    tablet_meta_pb->set_tablet_id(tablet_id());
912
593
    tablet_meta_pb->set_replica_id(replica_id());
913
593
    tablet_meta_pb->set_schema_hash(schema_hash());
914
593
    tablet_meta_pb->set_shard_id(shard_id());
915
593
    tablet_meta_pb->set_creation_time(creation_time());
916
593
    tablet_meta_pb->set_cumulative_layer_point(cumulative_layer_point());
917
593
    *(tablet_meta_pb->mutable_tablet_uid()) = tablet_uid().to_proto();
918
593
    tablet_meta_pb->set_tablet_type(_tablet_type);
919
593
    tablet_meta_pb->set_ttl_seconds(_ttl_seconds);
920
593
    switch (tablet_state()) {
921
44
    case TABLET_NOTREADY:
922
44
        tablet_meta_pb->set_tablet_state(PB_NOTREADY);
923
44
        break;
924
260
    case TABLET_RUNNING:
925
260
        tablet_meta_pb->set_tablet_state(PB_RUNNING);
926
260
        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
289
    case TABLET_SHUTDOWN:
934
289
        tablet_meta_pb->set_tablet_state(PB_SHUTDOWN);
935
289
        break;
936
593
    }
937
938
    // RowsetMetaPB is separated from TabletMetaPB
939
593
    if (!config::is_cloud_mode() || cloud_get_rowset_meta) {
940
11.2k
        for (const auto& [_, rs] : _rs_metas) {
941
11.2k
            rs->to_rowset_pb(tablet_meta_pb->add_rs_metas());
942
11.2k
        }
943
593
        for (const auto& [_, rs] : _stale_rs_metas) {
944
59
            rs->to_rowset_pb(tablet_meta_pb->add_stale_rs_metas());
945
59
        }
946
593
    }
947
948
593
    _schema->to_schema_pb(tablet_meta_pb->mutable_schema());
949
950
593
    tablet_meta_pb->set_in_restore_mode(in_restore_mode());
951
952
    // to avoid modify tablet meta to the greatest extend
953
593
    if (_preferred_rowset_type == BETA_ROWSET) {
954
593
        tablet_meta_pb->set_preferred_rowset_type(_preferred_rowset_type);
955
593
    }
956
593
    if (_storage_policy_id > 0) {
957
5
        tablet_meta_pb->set_storage_policy_id(_storage_policy_id);
958
5
    }
959
593
    if (_cooldown_meta_id.initialized()) {
960
5
        tablet_meta_pb->mutable_cooldown_meta_id()->CopyFrom(_cooldown_meta_id.to_proto());
961
5
    }
962
963
593
    tablet_meta_pb->set_enable_unique_key_merge_on_write(_enable_unique_key_merge_on_write);
964
965
593
    if (_enable_unique_key_merge_on_write) {
966
26
        std::set<RowsetId> stale_rs_ids;
967
26
        for (const auto& [_, rowset] : _stale_rs_metas) {
968
0
            stale_rs_ids.insert(rowset->rowset_id());
969
0
        }
970
26
        DeleteBitmapPB* delete_bitmap_pb = tablet_meta_pb->mutable_delete_bitmap();
971
26
        for (auto& [id, bitmap] : delete_bitmap().snapshot().delete_bitmap) {
972
2
            auto& [rowset_id, segment_id, ver] = id;
973
2
            if (stale_rs_ids.count(rowset_id) != 0) {
974
0
                continue;
975
0
            }
976
2
            delete_bitmap_pb->add_rowset_ids(rowset_id.to_string());
977
2
            delete_bitmap_pb->add_segment_ids(segment_id);
978
2
            delete_bitmap_pb->add_versions(ver);
979
2
            std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
980
2
            bitmap.write(bitmap_data.data());
981
2
            *(delete_bitmap_pb->add_segment_delete_bitmaps()) = std::move(bitmap_data);
982
2
        }
983
26
    }
984
593
    _binlog_config.to_pb(tablet_meta_pb->mutable_binlog_config());
985
593
    tablet_meta_pb->set_tablet_role(_tablet_role);
986
593
    tablet_meta_pb->set_compaction_policy(compaction_policy());
987
593
    tablet_meta_pb->set_time_series_compaction_goal_size_mbytes(
988
593
            time_series_compaction_goal_size_mbytes());
989
593
    tablet_meta_pb->set_time_series_compaction_file_count_threshold(
990
593
            time_series_compaction_file_count_threshold());
991
593
    tablet_meta_pb->set_time_series_compaction_time_threshold_seconds(
992
593
            time_series_compaction_time_threshold_seconds());
993
593
    tablet_meta_pb->set_time_series_compaction_empty_rowsets_threshold(
994
593
            time_series_compaction_empty_rowsets_threshold());
995
593
    tablet_meta_pb->set_time_series_compaction_level_threshold(
996
593
            time_series_compaction_level_threshold());
997
593
    tablet_meta_pb->set_vertical_compaction_num_columns_per_group(
998
593
            vertical_compaction_num_columns_per_group());
999
1000
593
    tablet_meta_pb->set_encryption_algorithm(_encryption_algorithm);
1001
593
}
1002
1003
2
void TabletMeta::to_json(string* json_string, json2pb::Pb2JsonOptions& options) {
1004
2
    TabletMetaPB tablet_meta_pb;
1005
2
    to_meta_pb(&tablet_meta_pb, false);
1006
2
    json2pb::ProtoMessageToJson(tablet_meta_pb, json_string, options);
1007
2
}
1008
1009
255
Version TabletMeta::max_version() const {
1010
255
    Version max_version = {-1, 0};
1011
3.37k
    for (const auto& [_, rs_meta] : _rs_metas) {
1012
3.37k
        if (rs_meta->end_version() > max_version.second) {
1013
229
            max_version = rs_meta->version();
1014
229
        }
1015
3.37k
    }
1016
255
    return max_version;
1017
255
}
1018
1019
0
size_t TabletMeta::version_count_cross_with_range(const Version& range) const {
1020
0
    size_t count = 0;
1021
0
    for (const auto& [_, rs_meta] : _rs_metas) {
1022
0
        if (!(range.first > rs_meta->version().second || range.second < rs_meta->version().first)) {
1023
0
            count++;
1024
0
        }
1025
0
    }
1026
0
    return count;
1027
0
}
1028
1029
9.23k
Status TabletMeta::add_rs_meta(const RowsetMetaSharedPtr& rs_meta) {
1030
    // check RowsetMeta is valid
1031
504k
    for (const auto& [_, rs] : _rs_metas) {
1032
504k
        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
504k
    }
1043
9.23k
    _rs_metas.emplace(rs_meta->version(), rs_meta);
1044
9.23k
    return Status::OK();
1045
9.23k
}
1046
1047
322
void TabletMeta::add_rowsets_unchecked(const std::vector<RowsetSharedPtr>& to_add) {
1048
899
    for (const auto& rs : to_add) {
1049
899
        _rs_metas.emplace(rs->rowset_meta()->version(), rs->rowset_meta());
1050
899
    }
1051
322
}
1052
1053
void TabletMeta::delete_rs_meta_by_version(const Version& version,
1054
0
                                           std::vector<RowsetMetaSharedPtr>* deleted_rs_metas) {
1055
0
    size_t rowset_cache_version_size = 0;
1056
0
    if (auto it = _rs_metas.find(version); it != _rs_metas.end()) {
1057
0
        if (deleted_rs_metas != nullptr) {
1058
0
            deleted_rs_metas->push_back(it->second);
1059
0
        }
1060
0
        auto rowset_id = it->second->rowset_id();
1061
0
        _rs_metas.erase(it);
1062
0
        if (_enable_unique_key_merge_on_write) {
1063
0
            rowset_cache_version_size = _delete_bitmap->remove_rowset_cache_version(rowset_id);
1064
0
        }
1065
0
        return;
1066
0
    }
1067
0
    _check_mow_rowset_cache_version_size(rowset_cache_version_size);
1068
0
}
1069
1070
void TabletMeta::modify_rs_metas(const std::vector<RowsetMetaSharedPtr>& to_add,
1071
                                 const std::vector<RowsetMetaSharedPtr>& to_delete,
1072
227
                                 bool same_version) {
1073
227
    size_t rowset_cache_version_size = 0;
1074
    // Remove to_delete rowsets from _rs_metas
1075
785
    for (auto rs_to_del : to_delete) {
1076
785
        if (auto it = _rs_metas.find(rs_to_del->version()); it != _rs_metas.end()) {
1077
785
            auto rowset_id = it->second->rowset_id();
1078
785
            _rs_metas.erase(it);
1079
785
            if (_enable_unique_key_merge_on_write) {
1080
194
                rowset_cache_version_size = _delete_bitmap->remove_rowset_cache_version(rowset_id);
1081
194
            }
1082
785
        }
1083
785
    }
1084
227
    if (!same_version) {
1085
        // put to_delete rowsets in _stale_rs_metas.
1086
686
        for (auto rs_to_del : to_delete) {
1087
686
            _stale_rs_metas.emplace(rs_to_del->version(), rs_to_del);
1088
686
        }
1089
139
    }
1090
1091
    // put to_add rowsets in _rs_metas.
1092
227
    for (auto rs_to_add : to_add) {
1093
123
        _rs_metas.emplace(rs_to_add->version(), rs_to_add);
1094
123
    }
1095
227
    _check_mow_rowset_cache_version_size(rowset_cache_version_size);
1096
227
}
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
5
void TabletMeta::revise_rs_metas(std::vector<RowsetMetaSharedPtr>&& rs_metas) {
1103
5
    {
1104
5
        std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
1105
5
        _rs_metas.clear();
1106
10
        for (auto& rs_meta : rs_metas) {
1107
10
            _rs_metas.emplace(rs_meta->version(), rs_meta);
1108
10
        }
1109
5
        _stale_rs_metas.clear();
1110
5
    }
1111
5
    if (_enable_unique_key_merge_on_write) {
1112
0
        _delete_bitmap->clear_rowset_cache_version();
1113
0
    }
1114
5
}
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
1
void TabletMeta::revise_delete_bitmap_unlocked(const DeleteBitmap& delete_bitmap) {
1122
1
    _delete_bitmap = std::make_unique<DeleteBitmap>(tablet_id());
1123
2
    for (const auto& [_, rs] : _rs_metas) {
1124
2
        DeleteBitmap rs_bm(tablet_id());
1125
2
        delete_bitmap.subset({rs->rowset_id(), 0, 0}, {rs->rowset_id(), UINT32_MAX, INT64_MAX},
1126
2
                             &rs_bm);
1127
2
        _delete_bitmap->merge(rs_bm);
1128
2
    }
1129
1
    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
1
}
1136
1137
5
void TabletMeta::delete_stale_rs_meta_by_version(const Version& version) {
1138
5
    _stale_rs_metas.erase(version);
1139
5
}
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
8
RowsetMetaSharedPtr TabletMeta::acquire_stale_rs_meta_by_version(const Version& version) const {
1149
8
    if (auto it = _stale_rs_metas.find(version); it != _stale_rs_metas.end()) {
1150
0
        return it->second;
1151
0
    }
1152
8
    return nullptr;
1153
8
}
1154
1155
79
Status TabletMeta::set_partition_id(int64_t partition_id) {
1156
79
    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
79
    _partition_id = partition_id;
1161
79
    return Status::OK();
1162
79
}
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
227
void TabletMeta::_check_mow_rowset_cache_version_size(size_t rowset_cache_version_size) {
1179
227
    if (_enable_unique_key_merge_on_write && config::enable_mow_verbose_log &&
1180
227
        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
227
}
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
197
static std::string agg_cache_key(int64_t tablet_id, const DeleteBitmap::BitmapKey& bmk) {
1253
197
    std::string ret(sizeof(tablet_id) + sizeof(bmk), '\0');
1254
197
    *reinterpret_cast<int64_t*>(ret.data()) = tablet_id;
1255
197
    auto t = reinterpret_cast<DeleteBitmap::BitmapKey*>(ret.data() + sizeof(tablet_id));
1256
197
    std::get<RowsetId>(*t).version = std::get<RowsetId>(bmk).version;
1257
197
    std::get<RowsetId>(*t).hi = std::get<RowsetId>(bmk).hi;
1258
197
    std::get<RowsetId>(*t).mi = std::get<RowsetId>(bmk).mi;
1259
197
    std::get<RowsetId>(*t).lo = std::get<RowsetId>(bmk).lo;
1260
197
    std::get<1>(*t) = std::get<1>(bmk);
1261
197
    std::get<2>(*t) = std::get<2>(bmk);
1262
197
    return ret;
1263
197
}
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
0
                                 DeleteBitmap::BitmapKey& bmk) {
1268
0
    const char* ptr = key_str.data();
1269
0
    tablet_id = *reinterpret_cast<const int64_t*>(ptr);
1270
0
    ptr += sizeof(tablet_id);
1271
0
    const auto* t = reinterpret_cast<const DeleteBitmap::BitmapKey*>(ptr);
1272
0
    std::get<RowsetId>(bmk).version = std::get<RowsetId>(*t).version;
1273
0
    std::get<RowsetId>(bmk).hi = std::get<RowsetId>(*t).hi;
1274
0
    std::get<RowsetId>(bmk).mi = std::get<RowsetId>(*t).mi;
1275
0
    std::get<RowsetId>(bmk).lo = std::get<RowsetId>(*t).lo;
1276
0
    std::get<1>(bmk) = std::get<1>(*t);
1277
0
    std::get<2>(bmk) = std::get<2>(*t);
1278
0
}
1279
1280
DeleteBitmapAggCache::DeleteBitmapAggCache(size_t capacity)
1281
1
        : LRUCachePolicy(CachePolicy::CacheType::DELETE_BITMAP_AGG_CACHE, capacity,
1282
1
                         LRUCacheType::SIZE, config::delete_bitmap_agg_cache_stale_sweep_time_sec,
1283
1
                         /*num_shards*/ 256,
1284
1
                         /*element_count_capacity*/ 0, /*enable_prune*/ true,
1285
1
                         /*is_lru_k*/ false) {}
1286
1287
323
DeleteBitmapAggCache* DeleteBitmapAggCache::instance() {
1288
323
    return ExecEnv::GetInstance()->delete_bitmap_agg_cache();
1289
323
}
1290
1291
1
DeleteBitmapAggCache* DeleteBitmapAggCache::create_instance(size_t capacity) {
1292
1
    return new DeleteBitmapAggCache(capacity);
1293
1
}
1294
1295
0
DeleteBitmap DeleteBitmapAggCache::snapshot(int64_t tablet_id) {
1296
0
    DeleteBitmap ret(tablet_id);
1297
0
    auto collector = [&](const LRUHandle* handle) {
1298
0
        auto key = handle->key().to_string();
1299
0
        int64_t key_tablet_id;
1300
0
        DeleteBitmap::BitmapKey bmk;
1301
0
        decode_agg_cache_key(key, key_tablet_id, bmk);
1302
0
        if (key_tablet_id == tablet_id) {
1303
0
            const auto& dbm = reinterpret_cast<DeleteBitmapAggCache::Value*>(handle->value)->bitmap;
1304
0
            ret.set(bmk, dbm);
1305
0
        }
1306
0
    };
1307
0
    DeleteBitmapAggCache::instance()->for_each_entry(collector);
1308
0
    return ret;
1309
0
}
1310
1311
1.18k
DeleteBitmap::DeleteBitmap(int64_t tablet_id) : _tablet_id(tablet_id) {}
1312
1313
29
DeleteBitmap::DeleteBitmap(const DeleteBitmap& o) {
1314
29
    std::shared_lock l1(o.lock);
1315
29
    delete_bitmap = o.delete_bitmap;
1316
29
    _tablet_id = o._tablet_id;
1317
29
}
1318
1319
0
DeleteBitmap& DeleteBitmap::operator=(const DeleteBitmap& o) {
1320
0
    if (this == &o) return *this;
1321
0
    if (this < &o) {
1322
0
        std::unique_lock l1(lock);
1323
0
        std::shared_lock l2(o.lock);
1324
0
        delete_bitmap = o.delete_bitmap;
1325
0
        _tablet_id = o._tablet_id;
1326
0
    } else {
1327
0
        std::shared_lock l2(o.lock);
1328
0
        std::unique_lock l1(lock);
1329
0
        delete_bitmap = o.delete_bitmap;
1330
0
        _tablet_id = o._tablet_id;
1331
0
    }
1332
0
    return *this;
1333
0
}
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
0
DeleteBitmap& DeleteBitmap::operator=(DeleteBitmap&& o) noexcept {
1343
0
    if (this == &o) return *this;
1344
0
    std::scoped_lock l(lock, o.lock, o._rowset_cache_version_lock);
1345
0
    delete_bitmap = std::move(o.delete_bitmap);
1346
0
    _tablet_id = std::move(o._tablet_id);
1347
0
    o._rowset_cache_version.clear();
1348
0
    return *this;
1349
0
}
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
29
DeleteBitmap DeleteBitmap::snapshot() const {
1381
29
    std::shared_lock l(lock);
1382
29
    return DeleteBitmap(*this);
1383
29
}
1384
1385
3
DeleteBitmap DeleteBitmap::snapshot(Version version) const {
1386
    // Take snapshot first, then remove keys greater than given version.
1387
3
    DeleteBitmap snapshot = this->snapshot();
1388
3
    auto it = snapshot.delete_bitmap.begin();
1389
412
    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
3
    return snapshot;
1397
3
}
1398
1399
463k
void DeleteBitmap::add(const BitmapKey& bmk, uint32_t row_id) {
1400
463k
    std::lock_guard l(lock);
1401
463k
    delete_bitmap[bmk].add(row_id);
1402
463k
}
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
8
void DeleteBitmap::remove(const BitmapKey& start, const BitmapKey& end) {
1413
8
    std::lock_guard l(lock);
1414
107
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end();) {
1415
101
        auto& [k, _] = *it;
1416
101
        if (k >= end) {
1417
2
            break;
1418
2
        }
1419
99
        it = delete_bitmap.erase(it);
1420
99
    }
1421
8
}
1422
1423
0
void DeleteBitmap::remove(const std::vector<std::tuple<BitmapKey, BitmapKey>>& key_ranges) {
1424
0
    std::lock_guard l(lock);
1425
0
    for (auto& [start, end] : key_ranges) {
1426
0
        for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end();) {
1427
0
            auto& [k, _] = *it;
1428
0
            if (k >= end) {
1429
0
                break;
1430
0
            }
1431
0
            it = delete_bitmap.erase(it);
1432
0
        }
1433
0
    }
1434
0
}
1435
1436
55
bool DeleteBitmap::contains(const BitmapKey& bmk, uint32_t row_id) const {
1437
55
    std::shared_lock l(lock);
1438
55
    auto it = delete_bitmap.find(bmk);
1439
55
    return it != delete_bitmap.end() && it->second.contains(row_id);
1440
55
}
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
82
uint64_t DeleteBitmap::cardinality() const {
1459
82
    std::shared_lock l(lock);
1460
82
    uint64_t res = 0;
1461
332
    for (auto entry : delete_bitmap) {
1462
332
        if (std::get<1>(entry.first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1463
332
            res += entry.second.cardinality();
1464
332
        }
1465
332
    }
1466
82
    return res;
1467
82
}
1468
1469
0
uint64_t DeleteBitmap::get_size() const {
1470
0
    std::shared_lock l(lock);
1471
0
    uint64_t charge = 0;
1472
0
    for (auto& [k, v] : delete_bitmap) {
1473
0
        if (std::get<1>(k) != DeleteBitmap::INVALID_SEGMENT_ID) {
1474
0
            charge += v.getSizeInBytes();
1475
0
        }
1476
0
    }
1477
0
    return charge;
1478
0
}
1479
1480
bool DeleteBitmap::contains_agg_with_cache_if_eligible(const BitmapKey& bmk,
1481
134
                                                       uint32_t row_id) const {
1482
134
    g_contains_agg_with_cache_if_eligible_total << 1;
1483
134
    int64_t start_version {0};
1484
134
    if (config::enable_mow_get_agg_by_cache) {
1485
134
        auto deleter = [&](Cache::Handle* handle) {
1486
0
            DeleteBitmapAggCache::instance()->release(handle);
1487
0
        };
1488
134
        std::unique_ptr<Cache::Handle, decltype(deleter)> dbm_handle(nullptr, deleter);
1489
134
        int64_t cached_version = 0;
1490
        // 1. try to lookup the desired key directly
1491
134
        dbm_handle.reset(DeleteBitmapAggCache::instance()->lookup(agg_cache_key(_tablet_id, bmk)));
1492
134
        if (dbm_handle != nullptr) {
1493
0
            cached_version = std::get<2>(bmk);
1494
134
        } else {
1495
            // 2. if not found, try to lookup with cached version
1496
134
            cached_version = _get_rowset_cache_version(bmk);
1497
134
            if (cached_version > 0) {
1498
0
                if (cached_version > std::get<2>(bmk)) {
1499
0
                    cached_version = 0;
1500
0
                } else {
1501
0
                    dbm_handle.reset(DeleteBitmapAggCache::instance()->lookup(agg_cache_key(
1502
0
                            _tablet_id, {std::get<0>(bmk), std::get<1>(bmk), cached_version})));
1503
0
                }
1504
0
            }
1505
134
        }
1506
134
        if (dbm_handle != nullptr) {
1507
0
            const auto& cached_dbm =
1508
0
                    reinterpret_cast<DeleteBitmapAggCache::Value*>(
1509
0
                            DeleteBitmapAggCache::instance()->value(dbm_handle.get()))
1510
0
                            ->bitmap;
1511
0
            if (cached_version == std::get<2>(bmk)) {
1512
0
                g_contains_agg_with_cache_if_eligible_full_hit << 1;
1513
0
            } else {
1514
0
                g_contains_agg_with_cache_if_eligible_partial_hit << 1;
1515
0
            }
1516
0
            if (cached_dbm.contains(row_id)) {
1517
0
                return true;
1518
0
            }
1519
0
            if (cached_version == std::get<2>(bmk)) {
1520
0
                return false;
1521
0
            }
1522
0
            start_version = cached_version + 1;
1523
0
        }
1524
134
    }
1525
134
    DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1526
134
    std::shared_lock l(lock);
1527
134
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1528
0
        auto& [k, bm] = *it;
1529
0
        if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1530
0
            std::get<2>(k) > std::get<2>(bmk)) {
1531
0
            break;
1532
0
        }
1533
0
        if (bm.contains(row_id)) {
1534
0
            return true;
1535
0
        }
1536
0
    }
1537
134
    return false;
1538
134
}
1539
1540
0
void DeleteBitmap::remove_sentinel_marks() {
1541
0
    std::lock_guard l(lock);
1542
0
    for (auto it = delete_bitmap.begin(), end = delete_bitmap.end(); it != end;) {
1543
0
        if (std::get<1>(it->first) == DeleteBitmap::INVALID_SEGMENT_ID) {
1544
0
            it = delete_bitmap.erase(it);
1545
0
        } else {
1546
0
            ++it;
1547
0
        }
1548
0
    }
1549
0
}
1550
1551
39
int DeleteBitmap::set(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1552
39
    std::lock_guard l(lock);
1553
39
    auto [_, inserted] = delete_bitmap.insert_or_assign(bmk, segment_delete_bitmap);
1554
39
    return inserted;
1555
39
}
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
3
                          DeleteBitmap* subset_rowset_map) const {
1574
3
    DCHECK(start < end);
1575
3
    std::shared_lock l(lock);
1576
26
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1577
25
        auto& [k, bm] = *it;
1578
25
        if (k >= end) {
1579
2
            break;
1580
2
        }
1581
23
        subset_rowset_map->set(k, bm);
1582
23
    }
1583
3
}
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
0
size_t DeleteBitmap::get_count_with_range(const BitmapKey& start, const BitmapKey& end) const {
1631
0
    DCHECK(start < end);
1632
0
    size_t count = 0;
1633
0
    std::shared_lock l(lock);
1634
0
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1635
0
        auto& [k, bm] = *it;
1636
0
        if (k >= end) {
1637
0
            break;
1638
0
        }
1639
0
        count++;
1640
0
    }
1641
0
    return count;
1642
0
}
1643
1644
6
void DeleteBitmap::merge(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1645
6
    std::lock_guard l(lock);
1646
6
    auto [iter, succ] = delete_bitmap.emplace(bmk, segment_delete_bitmap);
1647
6
    if (!succ) {
1648
0
        iter->second |= segment_delete_bitmap;
1649
0
    }
1650
6
}
1651
1652
9
void DeleteBitmap::merge(const DeleteBitmap& other) {
1653
9
    std::lock_guard l(lock);
1654
29
    for (auto& i : other.delete_bitmap) {
1655
29
        auto [j, succ] = this->delete_bitmap.insert(i);
1656
29
        if (!succ) j->second |= i.second;
1657
29
    }
1658
9
}
1659
1660
63
uint64_t DeleteBitmap::get_delete_bitmap_count() {
1661
63
    std::shared_lock l(lock);
1662
63
    uint64_t count = 0;
1663
383
    for (auto it = delete_bitmap.begin(); it != delete_bitmap.end(); it++) {
1664
320
        if (std::get<1>(it->first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1665
320
            count++;
1666
320
        }
1667
320
    }
1668
63
    return count;
1669
63
}
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
194
size_t DeleteBitmap::remove_rowset_cache_version(const RowsetId& rowset_id) {
1695
194
    std::lock_guard l(_rowset_cache_version_lock);
1696
194
    _rowset_cache_version.erase(rowset_id);
1697
194
    VLOG_DEBUG << "remove agg cache version for tablet=" << _tablet_id
1698
0
               << ", rowset=" << rowset_id.to_string();
1699
194
    return _rowset_cache_version.size();
1700
194
}
1701
1702
0
void DeleteBitmap::clear_rowset_cache_version() {
1703
0
    std::lock_guard l(_rowset_cache_version_lock);
1704
0
    _rowset_cache_version.clear();
1705
0
    VLOG_DEBUG << "clear agg cache version for tablet=" << _tablet_id;
1706
0
}
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
182
DeleteBitmap::Version DeleteBitmap::_get_rowset_cache_version(const BitmapKey& bmk) const {
1718
182
    std::shared_lock l(_rowset_cache_version_lock);
1719
182
    if (auto it = _rowset_cache_version.find(std::get<0>(bmk)); it != _rowset_cache_version.end()) {
1720
39
        auto& segment_cache_version = it->second;
1721
39
        if (auto it1 = segment_cache_version.find(std::get<1>(bmk));
1722
39
            it1 != segment_cache_version.end()) {
1723
10
            return it1->second;
1724
10
        }
1725
39
    }
1726
172
    return 0;
1727
182
}
1728
1729
0
DeleteBitmap DeleteBitmap::agg_cache_snapshot() {
1730
0
    return DeleteBitmapAggCache::instance()->snapshot(_tablet_id);
1731
0
}
1732
1733
942
void DeleteBitmap::set_tablet_id(int64_t tablet_id) {
1734
942
    _tablet_id = tablet_id;
1735
942
}
1736
1737
54
std::shared_ptr<roaring::Roaring> DeleteBitmap::get_agg(const BitmapKey& bmk) const {
1738
54
    std::string key_str = agg_cache_key(_tablet_id, bmk); // Cache key container
1739
54
    CacheKey key(key_str);
1740
54
    Cache::Handle* handle = DeleteBitmapAggCache::instance()->lookup(key);
1741
1742
54
    DeleteBitmapAggCache::Value* val =
1743
54
            handle == nullptr ? nullptr
1744
54
                              : reinterpret_cast<DeleteBitmapAggCache::Value*>(
1745
6
                                        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
54
    if (val == nullptr) { // Renew if needed, put a new Value to cache
1749
48
        val = new DeleteBitmapAggCache::Value();
1750
48
        Version start_version =
1751
48
                config::enable_mow_get_agg_by_cache ? _get_rowset_cache_version(bmk) : 0;
1752
48
        if (start_version > 0) {
1753
9
            Cache::Handle* handle2 = DeleteBitmapAggCache::instance()->lookup(
1754
9
                    agg_cache_key(_tablet_id, {std::get<0>(bmk), std::get<1>(bmk), start_version}));
1755
1756
9
            DBUG_EXECUTE_IF("DeleteBitmap::get_agg.cache_miss", {
1757
9
                if (handle2 != nullptr) {
1758
9
                    auto p = dp->param("percent", 0.3);
1759
9
                    std::mt19937 gen {std::random_device {}()};
1760
9
                    std::bernoulli_distribution inject_fault {p};
1761
9
                    if (inject_fault(gen)) {
1762
9
                        LOG_INFO("injection DeleteBitmap::get_agg.cache_miss, tablet_id={}",
1763
9
                                 _tablet_id);
1764
9
                        handle2 = nullptr;
1765
9
                    }
1766
9
                }
1767
9
            });
1768
9
            if (handle2 == nullptr || start_version > std::get<2>(bmk)) {
1769
0
                start_version = 0;
1770
9
            } else {
1771
9
                val->bitmap |= reinterpret_cast<DeleteBitmapAggCache::Value*>(
1772
9
                                       DeleteBitmapAggCache::instance()->value(handle2))
1773
9
                                       ->bitmap;
1774
9
                VLOG_DEBUG << "get agg cache version=" << start_version
1775
0
                           << " for tablet=" << _tablet_id
1776
0
                           << ", rowset=" << std::get<0>(bmk).to_string()
1777
0
                           << ", segment=" << std::get<1>(bmk);
1778
9
                start_version += 1;
1779
9
            }
1780
9
            if (handle2 != nullptr) {
1781
9
                DeleteBitmapAggCache::instance()->release(handle2);
1782
9
            }
1783
9
        }
1784
48
        {
1785
48
            std::shared_lock l(lock);
1786
48
            DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1787
87
            for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1788
84
                auto& [k, bm] = *it;
1789
84
                if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1790
84
                    std::get<2>(k) > std::get<2>(bmk)) {
1791
45
                    break;
1792
45
                }
1793
39
                val->bitmap |= bm;
1794
39
            }
1795
48
        }
1796
48
        size_t charge = val->bitmap.getSizeInBytes() + sizeof(DeleteBitmapAggCache::Value);
1797
48
        handle = DeleteBitmapAggCache::instance()->insert(key, val, charge, charge,
1798
48
                                                          CachePriority::NORMAL);
1799
48
        if (config::enable_mow_get_agg_by_cache && !val->bitmap.isEmpty()) {
1800
37
            std::lock_guard l(_rowset_cache_version_lock);
1801
            // this version is already agg
1802
37
            _rowset_cache_version[std::get<0>(bmk)][std::get<1>(bmk)] = std::get<2>(bmk);
1803
37
            VLOG_DEBUG << "set agg cache version=" << std::get<2>(bmk)
1804
0
                       << " for tablet=" << _tablet_id
1805
0
                       << ", rowset=" << std::get<0>(bmk).to_string()
1806
0
                       << ", segment=" << std::get<1>(bmk);
1807
37
        }
1808
48
        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
48
    }
1822
1823
    // It is natural for the cache to reclaim the underlying memory
1824
54
    return std::shared_ptr<roaring::Roaring>(
1825
54
            &val->bitmap, [handle](...) { DeleteBitmapAggCache::instance()->release(handle); });
1826
54
}
1827
1828
std::shared_ptr<roaring::Roaring> DeleteBitmap::get_agg_without_cache(
1829
4
        const BitmapKey& bmk, const int64_t start_version) const {
1830
4
    std::shared_ptr<roaring::Roaring> bitmap = std::make_shared<roaring::Roaring>();
1831
4
    std::shared_lock l(lock);
1832
4
    DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1833
24
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1834
23
        auto& [k, bm] = *it;
1835
23
        if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1836
23
            std::get<2>(k) > std::get<2>(bmk)) {
1837
3
            break;
1838
3
        }
1839
20
        *bitmap |= bm;
1840
20
    }
1841
4
    return bitmap;
1842
4
}
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
0
std::string tablet_state_name(TabletState state) {
1861
0
    switch (state) {
1862
0
    case TABLET_NOTREADY:
1863
0
        return "TABLET_NOTREADY";
1864
1865
0
    case TABLET_RUNNING:
1866
0
        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
0
    }
1880
0
}
1881
1882
} // namespace doris