Coverage Report

Created: 2026-03-13 19:41

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