Coverage Report

Created: 2025-11-20 07:31

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