Coverage Report

Created: 2025-09-29 18:47

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