Coverage Report

Created: 2025-12-31 15:01

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