Coverage Report

Created: 2026-01-04 17:54

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.30k
TabletMeta::~TabletMeta() {
132
1.30k
    if (_handle) {
133
1.11k
        TabletSchemaCache::instance()->release(_handle);
134
1.11k
    }
135
1.30k
}
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
    if (tcolumn.__isset.variant_enable_doc_mode) {
556
0
        column->set_variant_enable_doc_mode(tcolumn.variant_enable_doc_mode);
557
0
    }
558
2.21k
    if (tcolumn.__isset.variant_doc_materialization_min_rows) {
559
0
        column->set_variant_doc_materialization_min_rows(
560
0
                tcolumn.variant_doc_materialization_min_rows);
561
0
    }
562
2.21k
    if (tcolumn.__isset.variant_doc_hash_shard_count) {
563
0
        column->set_variant_doc_hash_shard_count(tcolumn.variant_doc_hash_shard_count);
564
0
    }
565
2.21k
}
566
567
0
void TabletMeta::remove_rowset_delete_bitmap(const RowsetId& rowset_id, const Version& version) {
568
0
    if (_enable_unique_key_merge_on_write) {
569
0
        delete_bitmap().remove({rowset_id, 0, 0}, {rowset_id, UINT32_MAX, 0});
570
0
        if (config::enable_mow_verbose_log) {
571
0
            LOG_INFO("delete rowset delete bitmap. tablet={}, rowset={}, version={}", tablet_id(),
572
0
                     rowset_id.to_string(), version.to_string());
573
0
        }
574
0
        size_t rowset_cache_version_size = delete_bitmap().remove_rowset_cache_version(rowset_id);
575
0
        _check_mow_rowset_cache_version_size(rowset_cache_version_size);
576
0
    }
577
0
}
578
579
4
Status TabletMeta::create_from_file(const string& file_path) {
580
4
    TabletMetaPB tablet_meta_pb;
581
4
    RETURN_IF_ERROR(load_from_file(file_path, &tablet_meta_pb));
582
4
    init_from_pb(tablet_meta_pb);
583
4
    return Status::OK();
584
4
}
585
586
12
Status TabletMeta::load_from_file(const string& file_path, TabletMetaPB* tablet_meta_pb) {
587
12
    FileHeader<TabletMetaPB> file_header(file_path);
588
    // In file_header.deserialize(), it validates file length, signature, checksum of protobuf.
589
12
    RETURN_IF_ERROR(file_header.deserialize());
590
12
    try {
591
12
        tablet_meta_pb->CopyFrom(file_header.message());
592
12
    } catch (const std::exception& e) {
593
0
        LOG(WARNING) << "Failed to copy protocol buffer object: " << e.what()
594
0
                     << ", file=" << file_path;
595
0
        return Status::Error<PARSE_PROTOBUF_ERROR>(
596
0
                "fail to copy protocol buffer object. file={}, error={}", file_path, e.what());
597
0
    }
598
12
    return Status::OK();
599
12
}
600
601
6
Status TabletMeta::create_from_buffer(const uint8_t* buffer, size_t buffer_size) {
602
6
    FileHeader<TabletMetaPB> file_header(""); // empty file path
603
6
    RETURN_IF_ERROR(file_header.deserialize_from_memory(buffer, buffer_size));
604
605
2
    TabletMetaPB tablet_meta_pb;
606
2
    try {
607
2
        tablet_meta_pb.CopyFrom(file_header.message());
608
2
    } catch (const std::exception& e) {
609
0
        LOG(WARNING) << "Failed to copy protocol buffer object from buffer: " << e.what();
610
0
        return Status::Error<ErrorCode::PARSE_PROTOBUF_ERROR>(
611
0
                "fail to copy protocol buffer object from buffer. error={}", e.what());
612
0
    }
613
614
2
    init_from_pb(tablet_meta_pb);
615
2
    return Status::OK();
616
2
}
617
618
std::string TabletMeta::construct_header_file_path(const string& schema_hash_path,
619
3
                                                   int64_t tablet_id) {
620
3
    std::stringstream header_name_stream;
621
3
    header_name_stream << schema_hash_path << "/" << tablet_id << ".hdr";
622
3
    return header_name_stream.str();
623
3
}
624
625
0
Status TabletMeta::save_as_json(const string& file_path) {
626
0
    std::string json_meta;
627
0
    json2pb::Pb2JsonOptions json_options;
628
0
    json_options.pretty_json = true;
629
0
    json_options.bytes_to_base64 = true;
630
0
    to_json(&json_meta, json_options);
631
    // save to file
632
0
    io::FileWriterPtr file_writer;
633
0
    RETURN_IF_ERROR(io::global_local_filesystem()->create_file(file_path, &file_writer));
634
0
    RETURN_IF_ERROR(file_writer->append(json_meta));
635
0
    RETURN_IF_ERROR(file_writer->close());
636
0
    return Status::OK();
637
0
}
638
639
230
Status TabletMeta::save(const string& file_path) {
640
230
    TabletMetaPB tablet_meta_pb;
641
230
    to_meta_pb(&tablet_meta_pb, false);
642
230
    return TabletMeta::save(file_path, tablet_meta_pb);
643
230
}
644
645
236
Status TabletMeta::save(const string& file_path, const TabletMetaPB& tablet_meta_pb) {
646
236
    DCHECK(!file_path.empty());
647
236
    FileHeader<TabletMetaPB> file_header(file_path);
648
236
    try {
649
236
        file_header.mutable_message()->CopyFrom(tablet_meta_pb);
650
236
    } catch (...) {
651
0
        LOG(WARNING) << "fail to copy protocol buffer object. file='" << file_path;
652
0
        return Status::Error<ErrorCode::INTERNAL_ERROR>(
653
0
                "fail to copy protocol buffer object. file={}", file_path);
654
0
    }
655
236
    RETURN_IF_ERROR(file_header.prepare());
656
236
    RETURN_IF_ERROR(file_header.serialize());
657
236
    return Status::OK();
658
236
}
659
660
572
Status TabletMeta::save_meta(DataDir* data_dir) {
661
572
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
662
572
    return _save_meta(data_dir);
663
572
}
664
665
572
Status TabletMeta::_save_meta(DataDir* data_dir) {
666
    // check if tablet uid is valid
667
572
    if (_tablet_uid.hi == 0 && _tablet_uid.lo == 0) {
668
0
        LOG(FATAL) << "tablet_uid is invalid"
669
0
                   << " tablet=" << tablet_id() << " _tablet_uid=" << _tablet_uid.to_string();
670
0
    }
671
572
    string meta_binary;
672
673
572
    auto t1 = MonotonicMicros();
674
572
    serialize(&meta_binary);
675
572
    auto t2 = MonotonicMicros();
676
572
    Status status = TabletMetaManager::save(data_dir, tablet_id(), schema_hash(), meta_binary);
677
572
    if (!status.ok()) {
678
0
        LOG(FATAL) << "fail to save tablet_meta. status=" << status << ", tablet_id=" << tablet_id()
679
0
                   << ", schema_hash=" << schema_hash();
680
0
    }
681
572
    auto t3 = MonotonicMicros();
682
572
    auto cost = t3 - t1;
683
572
    if (cost > 1 * 1000 * 1000) {
684
0
        LOG(INFO) << "save tablet(" << tablet_id() << ") meta too slow. serialize cost " << t2 - t1
685
0
                  << "(us), serialized binary size: " << meta_binary.length()
686
0
                  << "(bytes), write rocksdb cost " << t3 - t2 << "(us)";
687
0
    }
688
572
    return status;
689
572
}
690
691
577
void TabletMeta::serialize(string* meta_binary) {
692
577
    TabletMetaPB tablet_meta_pb;
693
577
    to_meta_pb(&tablet_meta_pb, false);
694
577
    if (tablet_meta_pb.partition_id() <= 0) {
695
468
        LOG(WARNING) << "invalid partition id " << tablet_meta_pb.partition_id() << " tablet "
696
468
                     << tablet_meta_pb.tablet_id();
697
468
    }
698
577
    DBUG_EXECUTE_IF("TabletMeta::serialize::zero_partition_id", {
699
577
        long partition_id = tablet_meta_pb.partition_id();
700
577
        tablet_meta_pb.set_partition_id(0);
701
577
        LOG(WARNING) << "set debug point TabletMeta::serialize::zero_partition_id old="
702
577
                     << partition_id << " new=" << tablet_meta_pb.DebugString();
703
577
    });
704
577
    bool serialize_success = tablet_meta_pb.SerializeToString(meta_binary);
705
577
    if (!_rs_metas.empty() || !_stale_rs_metas.empty()) {
706
577
        _avg_rs_meta_serialize_size =
707
577
                meta_binary->length() / (_rs_metas.size() + _stale_rs_metas.size());
708
577
        if (meta_binary->length() > config::tablet_meta_serialize_size_limit ||
709
577
            !serialize_success) {
710
0
            int64_t origin_meta_size = meta_binary->length();
711
0
            int64_t stale_rowsets_num = tablet_meta_pb.stale_rs_metas().size();
712
0
            tablet_meta_pb.clear_stale_rs_metas();
713
0
            meta_binary->clear();
714
0
            serialize_success = tablet_meta_pb.SerializeToString(meta_binary);
715
0
            LOG(WARNING) << "tablet meta serialization size exceeds limit: "
716
0
                         << config::tablet_meta_serialize_size_limit
717
0
                         << " clean up stale rowsets, tablet id: " << tablet_id()
718
0
                         << " stale rowset num: " << stale_rowsets_num
719
0
                         << " serialization size before clean " << origin_meta_size
720
0
                         << " serialization size after clean " << meta_binary->length();
721
0
        }
722
577
    }
723
724
577
    if (!serialize_success) {
725
0
        LOG(FATAL) << "failed to serialize meta " << tablet_id();
726
0
    }
727
577
}
728
729
461
Status TabletMeta::deserialize(std::string_view meta_binary) {
730
461
    TabletMetaPB tablet_meta_pb;
731
461
    bool parsed = tablet_meta_pb.ParseFromArray(meta_binary.data(),
732
461
                                                static_cast<int32_t>(meta_binary.size()));
733
461
    if (!parsed) {
734
0
        return Status::Error<INIT_FAILED>("parse tablet meta failed");
735
0
    }
736
461
    init_from_pb(tablet_meta_pb);
737
461
    return Status::OK();
738
461
}
739
740
1.11k
void TabletMeta::init_from_pb(const TabletMetaPB& tablet_meta_pb) {
741
1.11k
    _table_id = tablet_meta_pb.table_id();
742
1.11k
    _index_id = tablet_meta_pb.index_id();
743
1.11k
    _partition_id = tablet_meta_pb.partition_id();
744
1.11k
    _tablet_id = tablet_meta_pb.tablet_id();
745
1.11k
    _replica_id = tablet_meta_pb.replica_id();
746
1.11k
    _schema_hash = tablet_meta_pb.schema_hash();
747
1.11k
    _shard_id = tablet_meta_pb.shard_id();
748
1.11k
    _creation_time = tablet_meta_pb.creation_time();
749
1.11k
    _cumulative_layer_point = tablet_meta_pb.cumulative_layer_point();
750
1.11k
    _tablet_uid = TabletUid(tablet_meta_pb.tablet_uid());
751
1.11k
    _ttl_seconds = tablet_meta_pb.ttl_seconds();
752
1.11k
    if (tablet_meta_pb.has_tablet_type()) {
753
1.08k
        _tablet_type = tablet_meta_pb.tablet_type();
754
1.08k
    } else {
755
29
        _tablet_type = TabletTypePB::TABLET_TYPE_DISK;
756
29
    }
757
758
    // init _tablet_state
759
1.11k
    switch (tablet_meta_pb.tablet_state()) {
760
32
    case PB_NOTREADY:
761
32
        _tablet_state = TabletState::TABLET_NOTREADY;
762
32
        break;
763
859
    case PB_RUNNING:
764
859
        _tablet_state = TabletState::TABLET_RUNNING;
765
859
        break;
766
0
    case PB_TOMBSTONED:
767
0
        _tablet_state = TabletState::TABLET_TOMBSTONED;
768
0
        break;
769
0
    case PB_STOPPED:
770
0
        _tablet_state = TabletState::TABLET_STOPPED;
771
0
        break;
772
225
    case PB_SHUTDOWN:
773
225
        _tablet_state = TabletState::TABLET_SHUTDOWN;
774
225
        break;
775
0
    default:
776
0
        LOG(WARNING) << "tablet has no state. tablet=" << tablet_id()
777
0
                     << ", schema_hash=" << schema_hash();
778
1.11k
    }
779
780
    // init _schema
781
1.11k
    TabletSchemaSPtr schema = std::make_shared<TabletSchema>();
782
1.11k
    schema->init_from_pb(tablet_meta_pb.schema());
783
1.11k
    if (_handle) {
784
4
        TabletSchemaCache::instance()->release(_handle);
785
4
    }
786
1.11k
    auto pair = TabletSchemaCache::instance()->insert(schema->to_key());
787
1.11k
    _handle = pair.first;
788
1.11k
    _schema = pair.second;
789
790
1.11k
    if (tablet_meta_pb.has_enable_unique_key_merge_on_write()) {
791
1.08k
        _enable_unique_key_merge_on_write = tablet_meta_pb.enable_unique_key_merge_on_write();
792
1.08k
        _delete_bitmap->set_tablet_id(_tablet_id);
793
1.08k
    }
794
795
    // init _rs_metas
796
10.8k
    for (auto& it : tablet_meta_pb.rs_metas()) {
797
10.8k
        RowsetMetaSharedPtr rs_meta(new RowsetMeta());
798
10.8k
        rs_meta->init_from_pb(it);
799
10.8k
        _rs_metas.emplace(rs_meta->version(), rs_meta);
800
10.8k
    }
801
802
    // For mow table, delete bitmap of stale rowsets has not been persisted.
803
    // When be restart, query should not read the stale rowset, otherwise duplicate keys
804
    // will be read out. Therefore, we don't add them to _stale_rs_meta for mow table.
805
1.11k
    if (!config::skip_loading_stale_rowset_meta && !_enable_unique_key_merge_on_write) {
806
1.08k
        for (auto& it : tablet_meta_pb.stale_rs_metas()) {
807
0
            RowsetMetaSharedPtr rs_meta(new RowsetMeta());
808
0
            rs_meta->init_from_pb(it);
809
0
            _stale_rs_metas.emplace(rs_meta->version(), rs_meta);
810
0
        }
811
1.08k
    }
812
813
1.11k
    if (tablet_meta_pb.has_in_restore_mode()) {
814
1.08k
        _in_restore_mode = tablet_meta_pb.in_restore_mode();
815
1.08k
    }
816
817
1.11k
    if (tablet_meta_pb.has_preferred_rowset_type()) {
818
475
        _preferred_rowset_type = tablet_meta_pb.preferred_rowset_type();
819
475
    }
820
821
1.11k
    _storage_policy_id = tablet_meta_pb.storage_policy_id();
822
1.11k
    if (tablet_meta_pb.has_cooldown_meta_id()) {
823
0
        _cooldown_meta_id = tablet_meta_pb.cooldown_meta_id();
824
0
    }
825
826
1.11k
    if (tablet_meta_pb.has_delete_bitmap()) {
827
0
        int rst_ids_size = tablet_meta_pb.delete_bitmap().rowset_ids_size();
828
0
        int seg_ids_size = tablet_meta_pb.delete_bitmap().segment_ids_size();
829
0
        int versions_size = tablet_meta_pb.delete_bitmap().versions_size();
830
0
        int seg_maps_size = tablet_meta_pb.delete_bitmap().segment_delete_bitmaps_size();
831
0
        CHECK(rst_ids_size == seg_ids_size && seg_ids_size == seg_maps_size &&
832
0
              seg_maps_size == versions_size);
833
0
        for (int i = 0; i < rst_ids_size; ++i) {
834
0
            RowsetId rst_id;
835
0
            rst_id.init(tablet_meta_pb.delete_bitmap().rowset_ids(i));
836
0
            auto seg_id = tablet_meta_pb.delete_bitmap().segment_ids(i);
837
0
            auto ver = tablet_meta_pb.delete_bitmap().versions(i);
838
0
            auto bitmap = tablet_meta_pb.delete_bitmap().segment_delete_bitmaps(i).data();
839
0
            delete_bitmap().delete_bitmap[{rst_id, seg_id, ver}] = roaring::Roaring::read(bitmap);
840
0
        }
841
0
    }
842
843
1.11k
    if (tablet_meta_pb.has_binlog_config()) {
844
473
        _binlog_config = tablet_meta_pb.binlog_config();
845
473
    }
846
1.11k
    _compaction_policy = tablet_meta_pb.compaction_policy();
847
1.11k
    _time_series_compaction_goal_size_mbytes =
848
1.11k
            tablet_meta_pb.time_series_compaction_goal_size_mbytes();
849
1.11k
    _time_series_compaction_file_count_threshold =
850
1.11k
            tablet_meta_pb.time_series_compaction_file_count_threshold();
851
1.11k
    _time_series_compaction_time_threshold_seconds =
852
1.11k
            tablet_meta_pb.time_series_compaction_time_threshold_seconds();
853
1.11k
    _time_series_compaction_empty_rowsets_threshold =
854
1.11k
            tablet_meta_pb.time_series_compaction_empty_rowsets_threshold();
855
1.11k
    _time_series_compaction_level_threshold =
856
1.11k
            tablet_meta_pb.time_series_compaction_level_threshold();
857
858
1.11k
    if (tablet_meta_pb.has_encryption_algorithm()) {
859
1.08k
        _encryption_algorithm = tablet_meta_pb.encryption_algorithm();
860
1.08k
    }
861
1.11k
}
862
863
822
void TabletMeta::to_meta_pb(TabletMetaPB* tablet_meta_pb, bool cloud_get_rowset_meta) {
864
822
    tablet_meta_pb->set_table_id(table_id());
865
822
    tablet_meta_pb->set_index_id(index_id());
866
822
    tablet_meta_pb->set_partition_id(partition_id());
867
822
    tablet_meta_pb->set_tablet_id(tablet_id());
868
822
    tablet_meta_pb->set_replica_id(replica_id());
869
822
    tablet_meta_pb->set_schema_hash(schema_hash());
870
822
    tablet_meta_pb->set_shard_id(shard_id());
871
822
    tablet_meta_pb->set_creation_time(creation_time());
872
822
    tablet_meta_pb->set_cumulative_layer_point(cumulative_layer_point());
873
822
    *(tablet_meta_pb->mutable_tablet_uid()) = tablet_uid().to_proto();
874
822
    tablet_meta_pb->set_tablet_type(_tablet_type);
875
822
    tablet_meta_pb->set_ttl_seconds(_ttl_seconds);
876
822
    switch (tablet_state()) {
877
9
    case TABLET_NOTREADY:
878
9
        tablet_meta_pb->set_tablet_state(PB_NOTREADY);
879
9
        break;
880
332
    case TABLET_RUNNING:
881
332
        tablet_meta_pb->set_tablet_state(PB_RUNNING);
882
332
        break;
883
0
    case TABLET_TOMBSTONED:
884
0
        tablet_meta_pb->set_tablet_state(PB_TOMBSTONED);
885
0
        break;
886
0
    case TABLET_STOPPED:
887
0
        tablet_meta_pb->set_tablet_state(PB_STOPPED);
888
0
        break;
889
481
    case TABLET_SHUTDOWN:
890
481
        tablet_meta_pb->set_tablet_state(PB_SHUTDOWN);
891
481
        break;
892
822
    }
893
894
    // RowsetMetaPB is separated from TabletMetaPB
895
822
    if (!config::is_cloud_mode() || cloud_get_rowset_meta) {
896
21.6k
        for (const auto& [_, rs] : _rs_metas) {
897
21.6k
            rs->to_rowset_pb(tablet_meta_pb->add_rs_metas());
898
21.6k
        }
899
822
        for (const auto& [_, rs] : _stale_rs_metas) {
900
0
            rs->to_rowset_pb(tablet_meta_pb->add_stale_rs_metas());
901
0
        }
902
822
    }
903
904
822
    _schema->to_schema_pb(tablet_meta_pb->mutable_schema());
905
906
822
    tablet_meta_pb->set_in_restore_mode(in_restore_mode());
907
908
    // to avoid modify tablet meta to the greatest extend
909
822
    if (_preferred_rowset_type == BETA_ROWSET) {
910
822
        tablet_meta_pb->set_preferred_rowset_type(_preferred_rowset_type);
911
822
    }
912
822
    if (_storage_policy_id > 0) {
913
5
        tablet_meta_pb->set_storage_policy_id(_storage_policy_id);
914
5
    }
915
822
    if (_cooldown_meta_id.initialized()) {
916
5
        tablet_meta_pb->mutable_cooldown_meta_id()->CopyFrom(_cooldown_meta_id.to_proto());
917
5
    }
918
919
822
    tablet_meta_pb->set_enable_unique_key_merge_on_write(_enable_unique_key_merge_on_write);
920
921
822
    if (_enable_unique_key_merge_on_write) {
922
4
        std::set<RowsetId> stale_rs_ids;
923
4
        for (const auto& [_, rowset] : _stale_rs_metas) {
924
0
            stale_rs_ids.insert(rowset->rowset_id());
925
0
        }
926
4
        DeleteBitmapPB* delete_bitmap_pb = tablet_meta_pb->mutable_delete_bitmap();
927
4
        for (auto& [id, bitmap] : delete_bitmap().snapshot().delete_bitmap) {
928
2
            auto& [rowset_id, segment_id, ver] = id;
929
2
            if (stale_rs_ids.count(rowset_id) != 0) {
930
0
                continue;
931
0
            }
932
2
            delete_bitmap_pb->add_rowset_ids(rowset_id.to_string());
933
2
            delete_bitmap_pb->add_segment_ids(segment_id);
934
2
            delete_bitmap_pb->add_versions(ver);
935
2
            std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
936
2
            bitmap.write(bitmap_data.data());
937
2
            *(delete_bitmap_pb->add_segment_delete_bitmaps()) = std::move(bitmap_data);
938
2
        }
939
4
    }
940
822
    _binlog_config.to_pb(tablet_meta_pb->mutable_binlog_config());
941
822
    tablet_meta_pb->set_compaction_policy(compaction_policy());
942
822
    tablet_meta_pb->set_time_series_compaction_goal_size_mbytes(
943
822
            time_series_compaction_goal_size_mbytes());
944
822
    tablet_meta_pb->set_time_series_compaction_file_count_threshold(
945
822
            time_series_compaction_file_count_threshold());
946
822
    tablet_meta_pb->set_time_series_compaction_time_threshold_seconds(
947
822
            time_series_compaction_time_threshold_seconds());
948
822
    tablet_meta_pb->set_time_series_compaction_empty_rowsets_threshold(
949
822
            time_series_compaction_empty_rowsets_threshold());
950
822
    tablet_meta_pb->set_time_series_compaction_level_threshold(
951
822
            time_series_compaction_level_threshold());
952
953
822
    tablet_meta_pb->set_encryption_algorithm(_encryption_algorithm);
954
822
}
955
956
2
void TabletMeta::to_json(string* json_string, json2pb::Pb2JsonOptions& options) {
957
2
    TabletMetaPB tablet_meta_pb;
958
2
    to_meta_pb(&tablet_meta_pb, false);
959
2
    json2pb::ProtoMessageToJson(tablet_meta_pb, json_string, options);
960
2
}
961
962
165
Version TabletMeta::max_version() const {
963
165
    Version max_version = {-1, 0};
964
3.15k
    for (const auto& [_, rs_meta] : _rs_metas) {
965
3.15k
        if (rs_meta->end_version() > max_version.second) {
966
152
            max_version = rs_meta->version();
967
152
        }
968
3.15k
    }
969
165
    return max_version;
970
165
}
971
972
0
size_t TabletMeta::version_count_cross_with_range(const Version& range) const {
973
0
    size_t count = 0;
974
0
    for (const auto& [_, rs_meta] : _rs_metas) {
975
0
        if (!(range.first > rs_meta->version().second || range.second < rs_meta->version().first)) {
976
0
            count++;
977
0
        }
978
0
    }
979
0
    return count;
980
0
}
981
982
14.1k
Status TabletMeta::add_rs_meta(const RowsetMetaSharedPtr& rs_meta) {
983
    // check RowsetMeta is valid
984
690k
    for (const auto& [_, rs] : _rs_metas) {
985
690k
        if (rs->version() == rs_meta->version()) {
986
0
            if (rs->rowset_id() != rs_meta->rowset_id()) {
987
0
                return Status::Error<PUSH_VERSION_ALREADY_EXIST>(
988
0
                        "version already exist. rowset_id={}, version={}, tablet={}",
989
0
                        rs->rowset_id().to_string(), rs->version().to_string(), tablet_id());
990
0
            } else {
991
                // rowsetid,version is equal, it is a duplicate req, skip it
992
0
                return Status::OK();
993
0
            }
994
0
        }
995
690k
    }
996
14.1k
    _rs_metas.emplace(rs_meta->version(), rs_meta);
997
14.1k
    return Status::OK();
998
14.1k
}
999
1000
247
void TabletMeta::add_rowsets_unchecked(const std::vector<RowsetSharedPtr>& to_add) {
1001
732
    for (const auto& rs : to_add) {
1002
732
        _rs_metas.emplace(rs->rowset_meta()->version(), rs->rowset_meta());
1003
732
    }
1004
247
}
1005
1006
void TabletMeta::delete_rs_meta_by_version(const Version& version,
1007
0
                                           std::vector<RowsetMetaSharedPtr>* deleted_rs_metas) {
1008
0
    size_t rowset_cache_version_size = 0;
1009
0
    if (auto it = _rs_metas.find(version); it != _rs_metas.end()) {
1010
0
        if (deleted_rs_metas != nullptr) {
1011
0
            deleted_rs_metas->push_back(it->second);
1012
0
        }
1013
0
        auto rowset_id = it->second->rowset_id();
1014
0
        _rs_metas.erase(it);
1015
0
        if (_enable_unique_key_merge_on_write) {
1016
0
            rowset_cache_version_size = _delete_bitmap->remove_rowset_cache_version(rowset_id);
1017
0
        }
1018
0
        return;
1019
0
    }
1020
0
    _check_mow_rowset_cache_version_size(rowset_cache_version_size);
1021
0
}
1022
1023
void TabletMeta::modify_rs_metas(const std::vector<RowsetMetaSharedPtr>& to_add,
1024
                                 const std::vector<RowsetMetaSharedPtr>& to_delete,
1025
122
                                 bool same_version) {
1026
122
    size_t rowset_cache_version_size = 0;
1027
    // Remove to_delete rowsets from _rs_metas
1028
581
    for (auto rs_to_del : to_delete) {
1029
581
        if (auto it = _rs_metas.find(rs_to_del->version()); it != _rs_metas.end()) {
1030
581
            auto rowset_id = it->second->rowset_id();
1031
581
            _rs_metas.erase(it);
1032
581
            if (_enable_unique_key_merge_on_write) {
1033
180
                rowset_cache_version_size = _delete_bitmap->remove_rowset_cache_version(rowset_id);
1034
180
            }
1035
581
        }
1036
581
    }
1037
122
    if (!same_version) {
1038
        // put to_delete rowsets in _stale_rs_metas.
1039
560
        for (auto rs_to_del : to_delete) {
1040
560
            _stale_rs_metas.emplace(rs_to_del->version(), rs_to_del);
1041
560
        }
1042
101
    }
1043
1044
    // put to_add rowsets in _rs_metas.
1045
122
    for (auto rs_to_add : to_add) {
1046
23
        _rs_metas.emplace(rs_to_add->version(), rs_to_add);
1047
23
    }
1048
122
    _check_mow_rowset_cache_version_size(rowset_cache_version_size);
1049
122
}
1050
1051
// Use the passing "rs_metas" to replace the rs meta in this tablet meta
1052
// Also clear the _stale_rs_metas because this tablet meta maybe copyied from
1053
// an existing tablet before. Add after revise, only the passing "rs_metas"
1054
// is needed.
1055
5
void TabletMeta::revise_rs_metas(std::vector<RowsetMetaSharedPtr>&& rs_metas) {
1056
5
    {
1057
5
        std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
1058
5
        _rs_metas.clear();
1059
10
        for (auto& rs_meta : rs_metas) {
1060
10
            _rs_metas.emplace(rs_meta->version(), rs_meta);
1061
10
        }
1062
5
        _stale_rs_metas.clear();
1063
5
    }
1064
5
    if (_enable_unique_key_merge_on_write) {
1065
0
        _delete_bitmap->clear_rowset_cache_version();
1066
0
    }
1067
5
}
1068
1069
// This method should call after revise_rs_metas, since new rs_metas might be a subset
1070
// of original tablet, we should revise the delete_bitmap according to current rowset.
1071
//
1072
// Delete bitmap is protected by Tablet::_meta_lock, we don't need to acquire the
1073
// TabletMeta's _meta_lock
1074
1
void TabletMeta::revise_delete_bitmap_unlocked(const DeleteBitmap& delete_bitmap) {
1075
1
    _delete_bitmap = std::make_unique<DeleteBitmap>(tablet_id());
1076
2
    for (const auto& [_, rs] : _rs_metas) {
1077
2
        DeleteBitmap rs_bm(tablet_id());
1078
2
        delete_bitmap.subset({rs->rowset_id(), 0, 0}, {rs->rowset_id(), UINT32_MAX, INT64_MAX},
1079
2
                             &rs_bm);
1080
2
        _delete_bitmap->merge(rs_bm);
1081
2
    }
1082
1
    for (const auto& [_, rs] : _stale_rs_metas) {
1083
0
        DeleteBitmap rs_bm(tablet_id());
1084
0
        delete_bitmap.subset({rs->rowset_id(), 0, 0}, {rs->rowset_id(), UINT32_MAX, INT64_MAX},
1085
0
                             &rs_bm);
1086
0
        _delete_bitmap->merge(rs_bm);
1087
0
    }
1088
1
}
1089
1090
0
void TabletMeta::delete_stale_rs_meta_by_version(const Version& version) {
1091
0
    _stale_rs_metas.erase(version);
1092
0
}
1093
1094
0
RowsetMetaSharedPtr TabletMeta::acquire_rs_meta_by_version(const Version& version) const {
1095
0
    if (auto it = _rs_metas.find(version); it != _rs_metas.end()) {
1096
0
        return it->second;
1097
0
    }
1098
0
    return nullptr;
1099
0
}
1100
1101
8
RowsetMetaSharedPtr TabletMeta::acquire_stale_rs_meta_by_version(const Version& version) const {
1102
8
    if (auto it = _stale_rs_metas.find(version); it != _stale_rs_metas.end()) {
1103
0
        return it->second;
1104
0
    }
1105
8
    return nullptr;
1106
8
}
1107
1108
23
Status TabletMeta::set_partition_id(int64_t partition_id) {
1109
23
    if ((_partition_id > 0 && _partition_id != partition_id) || partition_id < 1) {
1110
0
        LOG(WARNING) << "cur partition id=" << _partition_id << " new partition id=" << partition_id
1111
0
                     << " not equal";
1112
0
    }
1113
23
    _partition_id = partition_id;
1114
23
    return Status::OK();
1115
23
}
1116
1117
0
void TabletMeta::clear_stale_rowset() {
1118
0
    _stale_rs_metas.clear();
1119
0
    if (_enable_unique_key_merge_on_write) {
1120
0
        _delete_bitmap->clear_rowset_cache_version();
1121
0
    }
1122
0
}
1123
1124
0
void TabletMeta::clear_rowsets() {
1125
0
    _rs_metas.clear();
1126
0
    if (_enable_unique_key_merge_on_write) {
1127
0
        _delete_bitmap->clear_rowset_cache_version();
1128
0
    }
1129
0
}
1130
1131
122
void TabletMeta::_check_mow_rowset_cache_version_size(size_t rowset_cache_version_size) {
1132
122
    if (_enable_unique_key_merge_on_write && config::enable_mow_verbose_log &&
1133
122
        rowset_cache_version_size > _rs_metas.size() + _stale_rs_metas.size()) {
1134
0
        std::stringstream ss;
1135
0
        auto rowset_ids = _delete_bitmap->get_rowset_cache_version();
1136
0
        std::set<std::string> tablet_rowset_ids;
1137
0
        {
1138
0
            std::shared_lock rlock(_meta_lock);
1139
0
            for (const auto& [_, rs_meta] : _rs_metas) {
1140
0
                tablet_rowset_ids.emplace(rs_meta->rowset_id().to_string());
1141
0
            }
1142
0
            for (const auto& [_, rs_meta] : _stale_rs_metas) {
1143
0
                tablet_rowset_ids.emplace(rs_meta->rowset_id().to_string());
1144
0
            }
1145
0
        }
1146
0
        for (const auto& rowset_id : rowset_ids) {
1147
0
            if (tablet_rowset_ids.find(rowset_id) == tablet_rowset_ids.end()) {
1148
0
                ss << rowset_id << ", ";
1149
0
            }
1150
0
        }
1151
        // size(rowset_cache_version) <= size(_rs_metas) + size(_stale_rs_metas) + size(_unused_rs)
1152
0
        std::string msg = fmt::format(
1153
0
                "tablet: {}, rowset_cache_version size: {}, "
1154
0
                "_rs_metas size: {}, _stale_rs_metas size: {}, delta: {}. rowset only in cache: {}",
1155
0
                _tablet_id, rowset_cache_version_size, _rs_metas.size(), _stale_rs_metas.size(),
1156
0
                rowset_cache_version_size - _rs_metas.size() - _stale_rs_metas.size(), ss.str());
1157
0
        LOG(INFO) << msg;
1158
0
    }
1159
122
}
1160
1161
3
bool operator==(const TabletMeta& a, const TabletMeta& b) {
1162
3
    if (a._table_id != b._table_id) return false;
1163
3
    if (a._index_id != b._index_id) return false;
1164
3
    if (a._partition_id != b._partition_id) return false;
1165
3
    if (a._tablet_id != b._tablet_id) return false;
1166
3
    if (a._replica_id != b._replica_id) return false;
1167
3
    if (a._schema_hash != b._schema_hash) return false;
1168
3
    if (a._shard_id != b._shard_id) return false;
1169
3
    if (a._creation_time != b._creation_time) return false;
1170
3
    if (a._cumulative_layer_point != b._cumulative_layer_point) return false;
1171
3
    if (a._tablet_uid != b._tablet_uid) return false;
1172
3
    if (a._tablet_type != b._tablet_type) return false;
1173
3
    if (a._tablet_state != b._tablet_state) return false;
1174
3
    if (*a._schema != *b._schema) return false;
1175
3
    if (a._rs_metas != b._rs_metas) return false;
1176
3
    if (a._in_restore_mode != b._in_restore_mode) return false;
1177
3
    if (a._preferred_rowset_type != b._preferred_rowset_type) return false;
1178
3
    if (a._storage_policy_id != b._storage_policy_id) return false;
1179
3
    if (a._compaction_policy != b._compaction_policy) return false;
1180
3
    if (a._time_series_compaction_goal_size_mbytes != b._time_series_compaction_goal_size_mbytes)
1181
0
        return false;
1182
3
    if (a._time_series_compaction_file_count_threshold !=
1183
3
        b._time_series_compaction_file_count_threshold)
1184
0
        return false;
1185
3
    if (a._time_series_compaction_time_threshold_seconds !=
1186
3
        b._time_series_compaction_time_threshold_seconds)
1187
0
        return false;
1188
3
    if (a._time_series_compaction_empty_rowsets_threshold !=
1189
3
        b._time_series_compaction_empty_rowsets_threshold)
1190
0
        return false;
1191
3
    if (a._time_series_compaction_level_threshold != b._time_series_compaction_level_threshold)
1192
0
        return false;
1193
3
    return true;
1194
3
}
1195
1196
0
bool operator!=(const TabletMeta& a, const TabletMeta& b) {
1197
0
    return !(a == b);
1198
0
}
1199
1200
// We cannot just copy the underlying memory to construct a string
1201
// due to equivalent objects may have different padding bytes.
1202
// Reading padding bytes is undefined behavior, neither copy nor
1203
// placement new will help simplify the code.
1204
// Refer to C11 standards §6.2.6.1/6 and §6.7.9/21 for more info.
1205
64
static std::string agg_cache_key(int64_t tablet_id, const DeleteBitmap::BitmapKey& bmk) {
1206
64
    std::string ret(sizeof(tablet_id) + sizeof(bmk), '\0');
1207
64
    *reinterpret_cast<int64_t*>(ret.data()) = tablet_id;
1208
64
    auto t = reinterpret_cast<DeleteBitmap::BitmapKey*>(ret.data() + sizeof(tablet_id));
1209
64
    std::get<RowsetId>(*t).version = std::get<RowsetId>(bmk).version;
1210
64
    std::get<RowsetId>(*t).hi = std::get<RowsetId>(bmk).hi;
1211
64
    std::get<RowsetId>(*t).mi = std::get<RowsetId>(bmk).mi;
1212
64
    std::get<RowsetId>(*t).lo = std::get<RowsetId>(bmk).lo;
1213
64
    std::get<1>(*t) = std::get<1>(bmk);
1214
64
    std::get<2>(*t) = std::get<2>(bmk);
1215
64
    return ret;
1216
64
}
1217
1218
// decode cache key info from a agg_cache_key
1219
static void decode_agg_cache_key(const std::string& key_str, int64_t& tablet_id,
1220
0
                                 DeleteBitmap::BitmapKey& bmk) {
1221
0
    const char* ptr = key_str.data();
1222
0
    tablet_id = *reinterpret_cast<const int64_t*>(ptr);
1223
0
    ptr += sizeof(tablet_id);
1224
0
    const auto* t = reinterpret_cast<const DeleteBitmap::BitmapKey*>(ptr);
1225
0
    std::get<RowsetId>(bmk).version = std::get<RowsetId>(*t).version;
1226
0
    std::get<RowsetId>(bmk).hi = std::get<RowsetId>(*t).hi;
1227
0
    std::get<RowsetId>(bmk).mi = std::get<RowsetId>(*t).mi;
1228
0
    std::get<RowsetId>(bmk).lo = std::get<RowsetId>(*t).lo;
1229
0
    std::get<1>(bmk) = std::get<1>(*t);
1230
0
    std::get<2>(bmk) = std::get<2>(*t);
1231
0
}
1232
1233
DeleteBitmapAggCache::DeleteBitmapAggCache(size_t capacity)
1234
1
        : LRUCachePolicy(CachePolicy::CacheType::DELETE_BITMAP_AGG_CACHE, capacity,
1235
1
                         LRUCacheType::SIZE, config::delete_bitmap_agg_cache_stale_sweep_time_sec,
1236
1
                         256) {}
1237
1238
190
DeleteBitmapAggCache* DeleteBitmapAggCache::instance() {
1239
190
    return ExecEnv::GetInstance()->delete_bitmap_agg_cache();
1240
190
}
1241
1242
1
DeleteBitmapAggCache* DeleteBitmapAggCache::create_instance(size_t capacity) {
1243
1
    return new DeleteBitmapAggCache(capacity);
1244
1
}
1245
1246
0
DeleteBitmap DeleteBitmapAggCache::snapshot(int64_t tablet_id) {
1247
0
    DeleteBitmap ret(tablet_id);
1248
0
    auto collector = [&](const LRUHandle* handle) {
1249
0
        auto key = handle->key().to_string();
1250
0
        int64_t key_tablet_id;
1251
0
        DeleteBitmap::BitmapKey bmk;
1252
0
        decode_agg_cache_key(key, key_tablet_id, bmk);
1253
0
        if (key_tablet_id == tablet_id) {
1254
0
            const auto& dbm = reinterpret_cast<DeleteBitmapAggCache::Value*>(handle->value)->bitmap;
1255
0
            ret.set(bmk, dbm);
1256
0
        }
1257
0
    };
1258
0
    DeleteBitmapAggCache::instance()->for_each_entry(collector);
1259
0
    return ret;
1260
0
}
1261
1262
1.20k
DeleteBitmap::DeleteBitmap(int64_t tablet_id) : _tablet_id(tablet_id) {}
1263
1264
7
DeleteBitmap::DeleteBitmap(const DeleteBitmap& o) {
1265
7
    std::shared_lock l1(o.lock);
1266
7
    delete_bitmap = o.delete_bitmap;
1267
7
    _tablet_id = o._tablet_id;
1268
7
}
1269
1270
0
DeleteBitmap& DeleteBitmap::operator=(const DeleteBitmap& o) {
1271
0
    if (this == &o) return *this;
1272
0
    if (this < &o) {
1273
0
        std::unique_lock l1(lock);
1274
0
        std::shared_lock l2(o.lock);
1275
0
        delete_bitmap = o.delete_bitmap;
1276
0
        _tablet_id = o._tablet_id;
1277
0
    } else {
1278
0
        std::shared_lock l2(o.lock);
1279
0
        std::unique_lock l1(lock);
1280
0
        delete_bitmap = o.delete_bitmap;
1281
0
        _tablet_id = o._tablet_id;
1282
0
    }
1283
0
    return *this;
1284
0
}
1285
1286
0
DeleteBitmap::DeleteBitmap(DeleteBitmap&& o) noexcept {
1287
0
    std::scoped_lock l(o.lock, o._rowset_cache_version_lock);
1288
0
    delete_bitmap = std::move(o.delete_bitmap);
1289
0
    _tablet_id = std::move(o._tablet_id);
1290
0
    o._rowset_cache_version.clear();
1291
0
}
1292
1293
0
DeleteBitmap& DeleteBitmap::operator=(DeleteBitmap&& o) noexcept {
1294
0
    if (this == &o) return *this;
1295
0
    std::scoped_lock l(lock, o.lock, o._rowset_cache_version_lock);
1296
0
    delete_bitmap = std::move(o.delete_bitmap);
1297
0
    _tablet_id = std::move(o._tablet_id);
1298
0
    o._rowset_cache_version.clear();
1299
0
    return *this;
1300
0
}
1301
1302
0
DeleteBitmap DeleteBitmap::from_pb(const DeleteBitmapPB& pb, int64_t tablet_id) {
1303
0
    size_t len = pb.rowset_ids().size();
1304
0
    DCHECK_EQ(len, pb.segment_ids().size());
1305
0
    DCHECK_EQ(len, pb.versions().size());
1306
0
    DeleteBitmap delete_bitmap(tablet_id);
1307
0
    for (int32_t i = 0; i < len; ++i) {
1308
0
        RowsetId rs_id;
1309
0
        rs_id.init(pb.rowset_ids(i));
1310
0
        BitmapKey key = {rs_id, pb.segment_ids(i), pb.versions(i)};
1311
0
        delete_bitmap.delete_bitmap[key] =
1312
0
                roaring::Roaring::read(pb.segment_delete_bitmaps(i).data());
1313
0
    }
1314
0
    return delete_bitmap;
1315
0
}
1316
1317
0
DeleteBitmapPB DeleteBitmap::to_pb() {
1318
0
    std::shared_lock l(lock);
1319
0
    DeleteBitmapPB ret;
1320
0
    for (const auto& [k, v] : delete_bitmap) {
1321
0
        ret.mutable_rowset_ids()->Add(std::get<0>(k).to_string());
1322
0
        ret.mutable_segment_ids()->Add(std::get<1>(k));
1323
0
        ret.mutable_versions()->Add(std::get<2>(k));
1324
0
        std::string bitmap_data(v.getSizeInBytes(), '\0');
1325
0
        v.write(bitmap_data.data());
1326
0
        ret.mutable_segment_delete_bitmaps()->Add(std::move(bitmap_data));
1327
0
    }
1328
0
    return ret;
1329
0
}
1330
1331
7
DeleteBitmap DeleteBitmap::snapshot() const {
1332
7
    std::shared_lock l(lock);
1333
7
    return DeleteBitmap(*this);
1334
7
}
1335
1336
3
DeleteBitmap DeleteBitmap::snapshot(Version version) const {
1337
    // Take snapshot first, then remove keys greater than given version.
1338
3
    DeleteBitmap snapshot = this->snapshot();
1339
3
    auto it = snapshot.delete_bitmap.begin();
1340
412
    while (it != snapshot.delete_bitmap.end()) {
1341
409
        if (std::get<2>(it->first) > version) {
1342
4
            it = snapshot.delete_bitmap.erase(it);
1343
405
        } else {
1344
405
            it++;
1345
405
        }
1346
409
    }
1347
3
    return snapshot;
1348
3
}
1349
1350
463k
void DeleteBitmap::add(const BitmapKey& bmk, uint32_t row_id) {
1351
463k
    std::lock_guard l(lock);
1352
463k
    delete_bitmap[bmk].add(row_id);
1353
463k
}
1354
1355
0
int DeleteBitmap::remove(const BitmapKey& bmk, uint32_t row_id) {
1356
0
    std::lock_guard l(lock);
1357
0
    auto it = delete_bitmap.find(bmk);
1358
0
    if (it == delete_bitmap.end()) return -1;
1359
0
    it->second.remove(row_id);
1360
0
    return 0;
1361
0
}
1362
1363
8
void DeleteBitmap::remove(const BitmapKey& start, const BitmapKey& end) {
1364
8
    std::lock_guard l(lock);
1365
107
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end();) {
1366
101
        auto& [k, _] = *it;
1367
101
        if (k >= end) {
1368
2
            break;
1369
2
        }
1370
99
        it = delete_bitmap.erase(it);
1371
99
    }
1372
8
}
1373
1374
0
void DeleteBitmap::remove(const std::vector<std::tuple<BitmapKey, BitmapKey>>& key_ranges) {
1375
0
    std::lock_guard l(lock);
1376
0
    for (auto& [start, end] : key_ranges) {
1377
0
        for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end();) {
1378
0
            auto& [k, _] = *it;
1379
0
            if (k >= end) {
1380
0
                break;
1381
0
            }
1382
0
            it = delete_bitmap.erase(it);
1383
0
        }
1384
0
    }
1385
0
}
1386
1387
6
bool DeleteBitmap::contains(const BitmapKey& bmk, uint32_t row_id) const {
1388
6
    std::shared_lock l(lock);
1389
6
    auto it = delete_bitmap.find(bmk);
1390
6
    return it != delete_bitmap.end() && it->second.contains(row_id);
1391
6
}
1392
1393
2
bool DeleteBitmap::contains_agg(const BitmapKey& bmk, uint32_t row_id) const {
1394
2
    return get_agg(bmk)->contains(row_id);
1395
2
}
1396
1397
0
bool DeleteBitmap::empty() const {
1398
0
    std::shared_lock l(lock);
1399
0
    return delete_bitmap.empty();
1400
0
}
1401
1402
63
uint64_t DeleteBitmap::cardinality() const {
1403
63
    std::shared_lock l(lock);
1404
63
    uint64_t res = 0;
1405
320
    for (auto entry : delete_bitmap) {
1406
320
        if (std::get<1>(entry.first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1407
320
            res += entry.second.cardinality();
1408
320
        }
1409
320
    }
1410
63
    return res;
1411
63
}
1412
1413
0
uint64_t DeleteBitmap::get_size() const {
1414
0
    std::shared_lock l(lock);
1415
0
    uint64_t charge = 0;
1416
0
    for (auto& [k, v] : delete_bitmap) {
1417
0
        if (std::get<1>(k) != DeleteBitmap::INVALID_SEGMENT_ID) {
1418
0
            charge += v.getSizeInBytes();
1419
0
        }
1420
0
    }
1421
0
    return charge;
1422
0
}
1423
1424
bool DeleteBitmap::contains_agg_with_cache_if_eligible(const BitmapKey& bmk,
1425
1
                                                       uint32_t row_id) const {
1426
1
    g_contains_agg_with_cache_if_eligible_total << 1;
1427
1
    int64_t start_version {0};
1428
1
    if (config::enable_mow_get_agg_by_cache) {
1429
1
        auto deleter = [&](Cache::Handle* handle) {
1430
0
            DeleteBitmapAggCache::instance()->release(handle);
1431
0
        };
1432
1
        std::unique_ptr<Cache::Handle, decltype(deleter)> dbm_handle(nullptr, deleter);
1433
1
        int64_t cached_version = 0;
1434
        // 1. try to lookup the desired key directly
1435
1
        dbm_handle.reset(DeleteBitmapAggCache::instance()->lookup(agg_cache_key(_tablet_id, bmk)));
1436
1
        if (dbm_handle != nullptr) {
1437
0
            cached_version = std::get<2>(bmk);
1438
1
        } else {
1439
            // 2. if not found, try to lookup with cached version
1440
1
            cached_version = _get_rowset_cache_version(bmk);
1441
1
            if (cached_version > 0) {
1442
0
                if (cached_version > std::get<2>(bmk)) {
1443
0
                    cached_version = 0;
1444
0
                } else {
1445
0
                    dbm_handle.reset(DeleteBitmapAggCache::instance()->lookup(agg_cache_key(
1446
0
                            _tablet_id, {std::get<0>(bmk), std::get<1>(bmk), cached_version})));
1447
0
                }
1448
0
            }
1449
1
        }
1450
1
        if (dbm_handle != nullptr) {
1451
0
            const auto& cached_dbm =
1452
0
                    reinterpret_cast<DeleteBitmapAggCache::Value*>(
1453
0
                            DeleteBitmapAggCache::instance()->value(dbm_handle.get()))
1454
0
                            ->bitmap;
1455
0
            if (cached_version == std::get<2>(bmk)) {
1456
0
                g_contains_agg_with_cache_if_eligible_full_hit << 1;
1457
0
            } else {
1458
0
                g_contains_agg_with_cache_if_eligible_partial_hit << 1;
1459
0
            }
1460
0
            if (cached_dbm.contains(row_id)) {
1461
0
                return true;
1462
0
            }
1463
0
            if (cached_version == std::get<2>(bmk)) {
1464
0
                return false;
1465
0
            }
1466
0
            start_version = cached_version + 1;
1467
0
        }
1468
1
    }
1469
1
    DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1470
1
    std::shared_lock l(lock);
1471
1
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1472
0
        auto& [k, bm] = *it;
1473
0
        if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1474
0
            std::get<2>(k) > std::get<2>(bmk)) {
1475
0
            break;
1476
0
        }
1477
0
        if (bm.contains(row_id)) {
1478
0
            return true;
1479
0
        }
1480
0
    }
1481
1
    return false;
1482
1
}
1483
1484
0
void DeleteBitmap::remove_sentinel_marks() {
1485
0
    std::lock_guard l(lock);
1486
0
    for (auto it = delete_bitmap.begin(), end = delete_bitmap.end(); it != end;) {
1487
0
        if (std::get<1>(it->first) == DeleteBitmap::INVALID_SEGMENT_ID) {
1488
0
            it = delete_bitmap.erase(it);
1489
0
        } else {
1490
0
            ++it;
1491
0
        }
1492
0
    }
1493
0
}
1494
1495
38
int DeleteBitmap::set(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1496
38
    std::lock_guard l(lock);
1497
38
    auto [_, inserted] = delete_bitmap.insert_or_assign(bmk, segment_delete_bitmap);
1498
38
    return inserted;
1499
38
}
1500
1501
7
int DeleteBitmap::get(const BitmapKey& bmk, roaring::Roaring* segment_delete_bitmap) const {
1502
7
    std::shared_lock l(lock);
1503
7
    auto it = delete_bitmap.find(bmk);
1504
7
    if (it == delete_bitmap.end()) return -1;
1505
7
    *segment_delete_bitmap = it->second; // copy
1506
7
    return 0;
1507
7
}
1508
1509
54
const roaring::Roaring* DeleteBitmap::get(const BitmapKey& bmk) const {
1510
54
    std::shared_lock l(lock);
1511
54
    auto it = delete_bitmap.find(bmk);
1512
54
    if (it == delete_bitmap.end()) return nullptr;
1513
41
    return &(it->second); // get address
1514
54
}
1515
1516
void DeleteBitmap::subset(const BitmapKey& start, const BitmapKey& end,
1517
3
                          DeleteBitmap* subset_rowset_map) const {
1518
3
    DCHECK(start < end);
1519
3
    std::shared_lock l(lock);
1520
26
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1521
25
        auto& [k, bm] = *it;
1522
25
        if (k >= end) {
1523
2
            break;
1524
2
        }
1525
23
        subset_rowset_map->set(k, bm);
1526
23
    }
1527
3
}
1528
1529
void DeleteBitmap::subset(std::vector<std::pair<RowsetId, int64_t>>& rowset_ids,
1530
                          int64_t start_version, int64_t end_version,
1531
0
                          DeleteBitmap* subset_delete_map) const {
1532
0
    DCHECK(start_version <= end_version);
1533
0
    for (auto& [rowset_id, _] : rowset_ids) {
1534
0
        BitmapKey start {rowset_id, 0, 0};
1535
0
        BitmapKey end {rowset_id, UINT32_MAX, end_version + 1};
1536
0
        std::shared_lock l(lock);
1537
0
        for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1538
0
            auto& [k, bm] = *it;
1539
0
            if (k >= end) {
1540
0
                break;
1541
0
            }
1542
0
            auto version = std::get<2>(k);
1543
0
            if (version >= start_version && version <= end_version) {
1544
0
                subset_delete_map->merge(k, bm);
1545
0
                VLOG_DEBUG << "subset delete bitmap, tablet=" << _tablet_id << ", version=["
1546
0
                           << start_version << ", " << end_version
1547
0
                           << "]. rowset=" << std::get<0>(k).to_string()
1548
0
                           << ", segment=" << std::get<1>(k) << ", version=" << version
1549
0
                           << ", cardinality=" << bm.cardinality();
1550
0
            }
1551
0
        }
1552
0
    }
1553
0
}
1554
1555
void DeleteBitmap::subset_and_agg(std::vector<std::pair<RowsetId, int64_t>>& rowset_ids,
1556
                                  int64_t start_version, int64_t end_version,
1557
1
                                  DeleteBitmap* subset_delete_map) const {
1558
1
    DCHECK(start_version <= end_version);
1559
2
    for (auto& [rowset_id, segment_num] : rowset_ids) {
1560
6
        for (int64_t seg_id = 0; seg_id < segment_num; ++seg_id) {
1561
4
            BitmapKey end {rowset_id, seg_id, end_version};
1562
4
            auto bm = get_agg_without_cache(end, start_version);
1563
4
            VLOG_DEBUG << "subset delete bitmap, tablet=" << _tablet_id << ", rowset=" << rowset_id
1564
0
                       << ", segment=" << seg_id << ", version=[" << start_version << "-"
1565
0
                       << end_version << "], cardinality=" << bm->cardinality();
1566
4
            if (bm->isEmpty()) {
1567
0
                continue;
1568
0
            }
1569
4
            subset_delete_map->merge(end, *bm);
1570
4
        }
1571
2
    }
1572
1
}
1573
1574
0
size_t DeleteBitmap::get_count_with_range(const BitmapKey& start, const BitmapKey& end) const {
1575
0
    DCHECK(start < end);
1576
0
    size_t count = 0;
1577
0
    std::shared_lock l(lock);
1578
0
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1579
0
        auto& [k, bm] = *it;
1580
0
        if (k >= end) {
1581
0
            break;
1582
0
        }
1583
0
        count++;
1584
0
    }
1585
0
    return count;
1586
0
}
1587
1588
6
void DeleteBitmap::merge(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1589
6
    std::lock_guard l(lock);
1590
6
    auto [iter, succ] = delete_bitmap.emplace(bmk, segment_delete_bitmap);
1591
6
    if (!succ) {
1592
0
        iter->second |= segment_delete_bitmap;
1593
0
    }
1594
6
}
1595
1596
9
void DeleteBitmap::merge(const DeleteBitmap& other) {
1597
9
    std::lock_guard l(lock);
1598
29
    for (auto& i : other.delete_bitmap) {
1599
29
        auto [j, succ] = this->delete_bitmap.insert(i);
1600
29
        if (!succ) j->second |= i.second;
1601
29
    }
1602
9
}
1603
1604
63
uint64_t DeleteBitmap::get_delete_bitmap_count() {
1605
63
    std::shared_lock l(lock);
1606
63
    uint64_t count = 0;
1607
383
    for (auto it = delete_bitmap.begin(); it != delete_bitmap.end(); it++) {
1608
320
        if (std::get<1>(it->first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1609
320
            count++;
1610
320
        }
1611
320
    }
1612
63
    return count;
1613
63
}
1614
1615
void DeleteBitmap::traverse_rowset_and_version(
1616
0
        const std::function<int(const RowsetId& rowsetId, int64_t version)>& func) const {
1617
0
    std::shared_lock l(lock);
1618
0
    auto it = delete_bitmap.cbegin();
1619
0
    while (it != delete_bitmap.cend()) {
1620
0
        RowsetId rowset_id = std::get<0>(it->first);
1621
0
        int64_t version = std::get<2>(it->first);
1622
0
        int result = func(rowset_id, version);
1623
0
        if (result == -2) {
1624
            // find next <rowset, version>
1625
0
            it++;
1626
0
        } else {
1627
            // find next <rowset>
1628
0
            it = delete_bitmap.upper_bound({rowset_id, std::numeric_limits<SegmentId>::max(),
1629
0
                                            std::numeric_limits<Version>::max()});
1630
0
        }
1631
0
    }
1632
0
}
1633
1634
0
bool DeleteBitmap::has_calculated_for_multi_segments(const RowsetId& rowset_id) const {
1635
0
    return contains({rowset_id, INVALID_SEGMENT_ID, TEMP_VERSION_COMMON}, ROWSET_SENTINEL_MARK);
1636
0
}
1637
1638
180
size_t DeleteBitmap::remove_rowset_cache_version(const RowsetId& rowset_id) {
1639
180
    std::lock_guard l(_rowset_cache_version_lock);
1640
180
    _rowset_cache_version.erase(rowset_id);
1641
180
    VLOG_DEBUG << "remove agg cache version for tablet=" << _tablet_id
1642
0
               << ", rowset=" << rowset_id.to_string();
1643
180
    return _rowset_cache_version.size();
1644
180
}
1645
1646
0
void DeleteBitmap::clear_rowset_cache_version() {
1647
0
    std::lock_guard l(_rowset_cache_version_lock);
1648
0
    _rowset_cache_version.clear();
1649
0
    VLOG_DEBUG << "clear agg cache version for tablet=" << _tablet_id;
1650
0
}
1651
1652
0
std::set<std::string> DeleteBitmap::get_rowset_cache_version() {
1653
0
    std::set<std::string> set;
1654
0
    std::shared_lock l(_rowset_cache_version_lock);
1655
0
    for (auto& [k, _] : _rowset_cache_version) {
1656
0
        set.insert(k.to_string());
1657
0
    }
1658
0
    return set;
1659
0
}
1660
1661
49
DeleteBitmap::Version DeleteBitmap::_get_rowset_cache_version(const BitmapKey& bmk) const {
1662
49
    std::shared_lock l(_rowset_cache_version_lock);
1663
49
    if (auto it = _rowset_cache_version.find(std::get<0>(bmk)); it != _rowset_cache_version.end()) {
1664
39
        auto& segment_cache_version = it->second;
1665
39
        if (auto it1 = segment_cache_version.find(std::get<1>(bmk));
1666
39
            it1 != segment_cache_version.end()) {
1667
10
            return it1->second;
1668
10
        }
1669
39
    }
1670
39
    return 0;
1671
49
}
1672
1673
0
DeleteBitmap DeleteBitmap::agg_cache_snapshot() {
1674
0
    return DeleteBitmapAggCache::instance()->snapshot(_tablet_id);
1675
0
}
1676
1677
1.08k
void DeleteBitmap::set_tablet_id(int64_t tablet_id) {
1678
1.08k
    _tablet_id = tablet_id;
1679
1.08k
}
1680
1681
54
std::shared_ptr<roaring::Roaring> DeleteBitmap::get_agg(const BitmapKey& bmk) const {
1682
54
    std::string key_str = agg_cache_key(_tablet_id, bmk); // Cache key container
1683
54
    CacheKey key(key_str);
1684
54
    Cache::Handle* handle = DeleteBitmapAggCache::instance()->lookup(key);
1685
1686
54
    DeleteBitmapAggCache::Value* val =
1687
54
            handle == nullptr ? nullptr
1688
54
                              : reinterpret_cast<DeleteBitmapAggCache::Value*>(
1689
6
                                        DeleteBitmapAggCache::instance()->value(handle));
1690
    // FIXME: do we need a mutex here to get rid of duplicated initializations
1691
    //        of cache entries in some cases?
1692
54
    if (val == nullptr) { // Renew if needed, put a new Value to cache
1693
48
        val = new DeleteBitmapAggCache::Value();
1694
48
        Version start_version =
1695
48
                config::enable_mow_get_agg_by_cache ? _get_rowset_cache_version(bmk) : 0;
1696
48
        if (start_version > 0) {
1697
9
            Cache::Handle* handle2 = DeleteBitmapAggCache::instance()->lookup(
1698
9
                    agg_cache_key(_tablet_id, {std::get<0>(bmk), std::get<1>(bmk), start_version}));
1699
1700
9
            DBUG_EXECUTE_IF("DeleteBitmap::get_agg.cache_miss", {
1701
9
                if (handle2 != nullptr) {
1702
9
                    auto p = dp->param("percent", 0.3);
1703
9
                    std::mt19937 gen {std::random_device {}()};
1704
9
                    std::bernoulli_distribution inject_fault {p};
1705
9
                    if (inject_fault(gen)) {
1706
9
                        LOG_INFO("injection DeleteBitmap::get_agg.cache_miss, tablet_id={}",
1707
9
                                 _tablet_id);
1708
9
                        handle2 = nullptr;
1709
9
                    }
1710
9
                }
1711
9
            });
1712
9
            if (handle2 == nullptr || start_version > std::get<2>(bmk)) {
1713
0
                start_version = 0;
1714
9
            } else {
1715
9
                val->bitmap |= reinterpret_cast<DeleteBitmapAggCache::Value*>(
1716
9
                                       DeleteBitmapAggCache::instance()->value(handle2))
1717
9
                                       ->bitmap;
1718
9
                VLOG_DEBUG << "get agg cache version=" << start_version
1719
0
                           << " for tablet=" << _tablet_id
1720
0
                           << ", rowset=" << std::get<0>(bmk).to_string()
1721
0
                           << ", segment=" << std::get<1>(bmk);
1722
9
                start_version += 1;
1723
9
            }
1724
9
            if (handle2 != nullptr) {
1725
9
                DeleteBitmapAggCache::instance()->release(handle2);
1726
9
            }
1727
9
        }
1728
48
        {
1729
48
            std::shared_lock l(lock);
1730
48
            DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1731
87
            for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1732
84
                auto& [k, bm] = *it;
1733
84
                if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1734
84
                    std::get<2>(k) > std::get<2>(bmk)) {
1735
45
                    break;
1736
45
                }
1737
39
                val->bitmap |= bm;
1738
39
            }
1739
48
        }
1740
48
        size_t charge = val->bitmap.getSizeInBytes() + sizeof(DeleteBitmapAggCache::Value);
1741
48
        handle = DeleteBitmapAggCache::instance()->insert(key, val, charge, charge,
1742
48
                                                          CachePriority::NORMAL);
1743
48
        if (config::enable_mow_get_agg_by_cache && !val->bitmap.isEmpty()) {
1744
37
            std::lock_guard l(_rowset_cache_version_lock);
1745
            // this version is already agg
1746
37
            _rowset_cache_version[std::get<0>(bmk)][std::get<1>(bmk)] = std::get<2>(bmk);
1747
37
            VLOG_DEBUG << "set agg cache version=" << std::get<2>(bmk)
1748
0
                       << " for tablet=" << _tablet_id
1749
0
                       << ", rowset=" << std::get<0>(bmk).to_string()
1750
0
                       << ", segment=" << std::get<1>(bmk);
1751
37
        }
1752
48
        if (start_version > 0 && config::enable_mow_get_agg_correctness_check_core) {
1753
0
            std::shared_ptr<roaring::Roaring> bitmap = get_agg_without_cache(bmk);
1754
0
            if (val->bitmap != *bitmap) {
1755
0
                CHECK(false) << ". get agg correctness check failed for tablet=" << _tablet_id
1756
0
                             << ", rowset=" << std::get<0>(bmk).to_string()
1757
0
                             << ", segment=" << std::get<1>(bmk) << ", version=" << std::get<2>(bmk)
1758
0
                             << ". start_version from cache=" << start_version
1759
0
                             << ", delete_bitmap cardinality with cache="
1760
0
                             << val->bitmap.cardinality()
1761
0
                             << ", delete_bitmap cardinality without cache="
1762
0
                             << bitmap->cardinality();
1763
0
            }
1764
0
        }
1765
48
    }
1766
1767
    // It is natural for the cache to reclaim the underlying memory
1768
54
    return std::shared_ptr<roaring::Roaring>(
1769
54
            &val->bitmap, [handle](...) { DeleteBitmapAggCache::instance()->release(handle); });
1770
54
}
1771
1772
std::shared_ptr<roaring::Roaring> DeleteBitmap::get_agg_without_cache(
1773
4
        const BitmapKey& bmk, const int64_t start_version) const {
1774
4
    std::shared_ptr<roaring::Roaring> bitmap = std::make_shared<roaring::Roaring>();
1775
4
    std::shared_lock l(lock);
1776
4
    DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1777
24
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1778
23
        auto& [k, bm] = *it;
1779
23
        if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1780
23
            std::get<2>(k) > std::get<2>(bmk)) {
1781
3
            break;
1782
3
        }
1783
20
        *bitmap |= bm;
1784
20
    }
1785
4
    return bitmap;
1786
4
}
1787
1788
0
DeleteBitmap DeleteBitmap::diffset(const std::set<BitmapKey>& key_set) const {
1789
0
    std::shared_lock l(lock);
1790
0
    auto diff_key_set_view =
1791
0
            delete_bitmap | std::ranges::views::transform([](const auto& kv) { return kv.first; }) |
1792
0
            std::ranges::views::filter(
1793
0
                    [&key_set](const auto& key) { return !key_set.contains(key); });
1794
1795
0
    DeleteBitmap dbm(_tablet_id);
1796
0
    for (const auto& key : diff_key_set_view) {
1797
0
        const auto* bitmap = get(key);
1798
0
        DCHECK_NE(bitmap, nullptr);
1799
0
        dbm.delete_bitmap[key] = *bitmap;
1800
0
    }
1801
0
    return dbm;
1802
0
}
1803
1804
0
std::string tablet_state_name(TabletState state) {
1805
0
    switch (state) {
1806
0
    case TABLET_NOTREADY:
1807
0
        return "TABLET_NOTREADY";
1808
1809
0
    case TABLET_RUNNING:
1810
0
        return "TABLET_RUNNING";
1811
1812
0
    case TABLET_TOMBSTONED:
1813
0
        return "TABLET_TOMBSTONED";
1814
1815
0
    case TABLET_STOPPED:
1816
0
        return "TABLET_STOPPED";
1817
1818
0
    case TABLET_SHUTDOWN:
1819
0
        return "TABLET_SHUTDOWN";
1820
1821
0
    default:
1822
0
        return "TabletState(" + std::to_string(state) + ")";
1823
0
    }
1824
0
}
1825
1826
#include "common/compile_check_end.h"
1827
} // namespace doris