Coverage Report

Created: 2026-08-07 19:51

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