Coverage Report

Created: 2025-09-16 21:59

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.11k
TabletMeta::~TabletMeta() {
128
1.11k
    if (_handle) {
129
992
        TabletSchemaCache::instance()->release(_handle);
130
992
    }
131
1.11k
}
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
495
        : _tablet_uid(0, 0),
154
495
          _schema(new TabletSchema),
155
495
          _delete_bitmap(new DeleteBitmap(tablet_id)) {
156
495
    TabletMetaPB tablet_meta_pb;
157
495
    tablet_meta_pb.set_table_id(table_id);
158
495
    tablet_meta_pb.set_partition_id(partition_id);
159
495
    tablet_meta_pb.set_tablet_id(tablet_id);
160
495
    tablet_meta_pb.set_replica_id(replica_id);
161
495
    tablet_meta_pb.set_schema_hash(schema_hash);
162
495
    tablet_meta_pb.set_shard_id(shard_id);
163
    // Persist the creation time, but it is not used
164
495
    tablet_meta_pb.set_creation_time(time(nullptr));
165
495
    tablet_meta_pb.set_cumulative_layer_point(-1);
166
495
    tablet_meta_pb.set_tablet_state(PB_RUNNING);
167
495
    *(tablet_meta_pb.mutable_tablet_uid()) = tablet_uid.to_proto();
168
495
    tablet_meta_pb.set_tablet_type(tabletType == TTabletType::TABLET_TYPE_DISK
169
495
                                           ? TabletTypePB::TABLET_TYPE_DISK
170
495
                                           : TabletTypePB::TABLET_TYPE_MEMORY);
171
495
    tablet_meta_pb.set_enable_unique_key_merge_on_write(enable_unique_key_merge_on_write);
172
495
    tablet_meta_pb.set_storage_policy_id(storage_policy_id);
173
495
    tablet_meta_pb.set_compaction_policy(compaction_policy);
174
495
    tablet_meta_pb.set_time_series_compaction_goal_size_mbytes(
175
495
            time_series_compaction_goal_size_mbytes);
176
495
    tablet_meta_pb.set_time_series_compaction_file_count_threshold(
177
495
            time_series_compaction_file_count_threshold);
178
495
    tablet_meta_pb.set_time_series_compaction_time_threshold_seconds(
179
495
            time_series_compaction_time_threshold_seconds);
180
495
    tablet_meta_pb.set_time_series_compaction_empty_rowsets_threshold(
181
495
            time_series_compaction_empty_rowsets_threshold);
182
495
    tablet_meta_pb.set_time_series_compaction_level_threshold(
183
495
            time_series_compaction_level_threshold);
184
495
    TabletSchemaPB* schema = tablet_meta_pb.mutable_schema();
185
495
    schema->set_num_short_key_columns(tablet_schema.short_key_column_count);
186
495
    schema->set_num_rows_per_row_block(config::default_num_rows_per_column_file_block);
187
495
    schema->set_sequence_col_idx(tablet_schema.sequence_col_idx);
188
495
    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
90
    default:
199
90
        LOG(WARNING) << "unknown tablet keys type";
200
90
        break;
201
495
    }
202
    // compress_kind used to compress segment files
203
495
    schema->set_compress_kind(COMPRESS_LZ4);
204
205
    // compression_type used to compress segment page
206
495
    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
495
    case TCompressionType::LZ4F:
217
495
        schema->set_compression_type(segment_v2::LZ4F);
218
495
        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
495
    }
229
230
495
    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
495
    case TInvertedIndexFileStorageFormat::V2:
235
495
        schema->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V2);
236
495
        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
495
    }
244
245
495
    switch (tablet_schema.sort_type) {
246
0
    case TSortType::type::ZORDER:
247
0
        schema->set_sort_type(SortType::ZORDER);
248
0
        break;
249
495
    default:
250
495
        schema->set_sort_type(SortType::LEXICAL);
251
495
    }
252
495
    schema->set_sort_col_num(tablet_schema.sort_col_num);
253
495
    for (const auto& i : tablet_schema.cluster_key_uids) {
254
2
        schema->add_cluster_key_uids(i);
255
2
    }
256
495
    tablet_meta_pb.set_in_restore_mode(false);
257
258
    // set column information
259
495
    uint32_t col_ordinal = 0;
260
495
    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
495
    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
495
    schema->set_next_column_unique_id(next_unique_id);
339
495
    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
495
    if (tablet_schema.__isset.is_in_memory) {
344
0
        schema->set_is_in_memory(tablet_schema.is_in_memory);
345
0
    }
346
347
495
    if (tablet_schema.__isset.disable_auto_compaction) {
348
0
        schema->set_disable_auto_compaction(tablet_schema.disable_auto_compaction);
349
0
    }
350
351
495
    if (tablet_schema.__isset.variant_enable_flatten_nested) {
352
495
        schema->set_enable_variant_flatten_nested(tablet_schema.variant_enable_flatten_nested);
353
495
    }
354
355
495
    if (tablet_schema.__isset.enable_single_replica_compaction) {
356
495
        schema->set_enable_single_replica_compaction(
357
495
                tablet_schema.enable_single_replica_compaction);
358
495
    }
359
360
495
    if (tablet_schema.__isset.delete_sign_idx) {
361
495
        schema->set_delete_sign_idx(tablet_schema.delete_sign_idx);
362
495
    }
363
495
    if (tablet_schema.__isset.store_row_column) {
364
495
        schema->set_store_row_column(tablet_schema.store_row_column);
365
495
    }
366
495
    if (tablet_schema.__isset.row_store_page_size) {
367
495
        schema->set_row_store_page_size(tablet_schema.row_store_page_size);
368
495
    }
369
495
    if (tablet_schema.__isset.storage_page_size) {
370
495
        schema->set_storage_page_size(tablet_schema.storage_page_size);
371
495
    }
372
495
    if (tablet_schema.__isset.storage_dict_page_size) {
373
495
        schema->set_storage_dict_page_size(tablet_schema.storage_dict_page_size);
374
495
    }
375
495
    if (tablet_schema.__isset.skip_write_index_on_load) {
376
495
        schema->set_skip_write_index_on_load(tablet_schema.skip_write_index_on_load);
377
495
    }
378
495
    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
495
    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
495
    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
495
    default:
396
495
        tablet_meta_pb.set_encryption_algorithm(EncryptionAlgorithmPB::PLAINTEXT);
397
495
    }
398
399
495
    init_from_pb(tablet_meta_pb);
400
495
}
401
402
TabletMeta::TabletMeta(const TabletMeta& b)
403
20
        : MetadataAdder(b),
404
20
          _table_id(b._table_id),
405
20
          _index_id(b._index_id),
406
20
          _partition_id(b._partition_id),
407
20
          _tablet_id(b._tablet_id),
408
20
          _replica_id(b._replica_id),
409
20
          _schema_hash(b._schema_hash),
410
20
          _shard_id(b._shard_id),
411
20
          _creation_time(b._creation_time),
412
20
          _cumulative_layer_point(b._cumulative_layer_point),
413
20
          _tablet_uid(b._tablet_uid),
414
20
          _tablet_type(b._tablet_type),
415
20
          _tablet_state(b._tablet_state),
416
20
          _schema(b._schema),
417
20
          _rs_metas(b._rs_metas),
418
20
          _stale_rs_metas(b._stale_rs_metas),
419
20
          _in_restore_mode(b._in_restore_mode),
420
20
          _preferred_rowset_type(b._preferred_rowset_type),
421
20
          _storage_policy_id(b._storage_policy_id),
422
20
          _cooldown_meta_id(b._cooldown_meta_id),
423
20
          _enable_unique_key_merge_on_write(b._enable_unique_key_merge_on_write),
424
20
          _delete_bitmap(b._delete_bitmap),
425
20
          _binlog_config(b._binlog_config),
426
20
          _compaction_policy(b._compaction_policy),
427
20
          _time_series_compaction_goal_size_mbytes(b._time_series_compaction_goal_size_mbytes),
428
          _time_series_compaction_file_count_threshold(
429
20
                  b._time_series_compaction_file_count_threshold),
430
          _time_series_compaction_time_threshold_seconds(
431
20
                  b._time_series_compaction_time_threshold_seconds),
432
          _time_series_compaction_empty_rowsets_threshold(
433
20
                  b._time_series_compaction_empty_rowsets_threshold),
434
20
          _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
995
void TabletMeta::init_from_pb(const TabletMetaPB& tablet_meta_pb) {
696
995
    _table_id = tablet_meta_pb.table_id();
697
995
    _index_id = tablet_meta_pb.index_id();
698
995
    _partition_id = tablet_meta_pb.partition_id();
699
995
    _tablet_id = tablet_meta_pb.tablet_id();
700
995
    _replica_id = tablet_meta_pb.replica_id();
701
995
    _schema_hash = tablet_meta_pb.schema_hash();
702
995
    _shard_id = tablet_meta_pb.shard_id();
703
995
    _creation_time = tablet_meta_pb.creation_time();
704
995
    _cumulative_layer_point = tablet_meta_pb.cumulative_layer_point();
705
995
    _tablet_uid = TabletUid(tablet_meta_pb.tablet_uid());
706
995
    _ttl_seconds = tablet_meta_pb.ttl_seconds();
707
995
    if (tablet_meta_pb.has_tablet_type()) {
708
969
        _tablet_type = tablet_meta_pb.tablet_type();
709
969
    } else {
710
26
        _tablet_type = TabletTypePB::TABLET_TYPE_DISK;
711
26
    }
712
713
    // init _tablet_state
714
995
    switch (tablet_meta_pb.tablet_state()) {
715
28
    case PB_NOTREADY:
716
28
        _tablet_state = TabletState::TABLET_NOTREADY;
717
28
        break;
718
742
    case PB_RUNNING:
719
742
        _tablet_state = TabletState::TABLET_RUNNING;
720
742
        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
995
    }
734
735
    // init _schema
736
995
    TabletSchemaSPtr schema = std::make_shared<TabletSchema>();
737
995
    schema->init_from_pb(tablet_meta_pb.schema());
738
995
    if (_handle) {
739
3
        TabletSchemaCache::instance()->release(_handle);
740
3
    }
741
995
    auto pair = TabletSchemaCache::instance()->insert(schema->to_key());
742
995
    _handle = pair.first;
743
995
    _schema = pair.second;
744
745
995
    if (tablet_meta_pb.has_enable_unique_key_merge_on_write()) {
746
969
        _enable_unique_key_merge_on_write = tablet_meta_pb.enable_unique_key_merge_on_write();
747
969
        _delete_bitmap->set_tablet_id(_tablet_id);
748
969
    }
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.push_back(std::move(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
995
    if (!config::skip_loading_stale_rowset_meta && !_enable_unique_key_merge_on_write) {
761
960
        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.push_back(std::move(rs_meta));
765
0
        }
766
960
    }
767
768
995
    if (tablet_meta_pb.has_in_restore_mode()) {
769
969
        _in_restore_mode = tablet_meta_pb.in_restore_mode();
770
969
    }
771
772
995
    if (tablet_meta_pb.has_preferred_rowset_type()) {
773
474
        _preferred_rowset_type = tablet_meta_pb.preferred_rowset_type();
774
474
    }
775
776
995
    _storage_policy_id = tablet_meta_pb.storage_policy_id();
777
995
    if (tablet_meta_pb.has_cooldown_meta_id()) {
778
0
        _cooldown_meta_id = tablet_meta_pb.cooldown_meta_id();
779
0
    }
780
781
995
    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
995
    if (tablet_meta_pb.has_binlog_config()) {
799
472
        _binlog_config = tablet_meta_pb.binlog_config();
800
472
    }
801
995
    _compaction_policy = tablet_meta_pb.compaction_policy();
802
995
    _time_series_compaction_goal_size_mbytes =
803
995
            tablet_meta_pb.time_series_compaction_goal_size_mbytes();
804
995
    _time_series_compaction_file_count_threshold =
805
995
            tablet_meta_pb.time_series_compaction_file_count_threshold();
806
995
    _time_series_compaction_time_threshold_seconds =
807
995
            tablet_meta_pb.time_series_compaction_time_threshold_seconds();
808
995
    _time_series_compaction_empty_rowsets_threshold =
809
995
            tablet_meta_pb.time_series_compaction_empty_rowsets_threshold();
810
995
    _time_series_compaction_level_threshold =
811
995
            tablet_meta_pb.time_series_compaction_level_threshold();
812
813
995
    if (tablet_meta_pb.has_encryption_algorithm()) {
814
967
        _encryption_algorithm = tablet_meta_pb.encryption_algorithm();
815
967
    }
816
995
}
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 (auto& rs : _rs_metas) {
852
21.6k
            rs->to_rowset_pb(tablet_meta_pb->add_rs_metas());
853
21.6k
        }
854
814
        for (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
193
    for (auto& rs_meta : _rs_metas) {
920
193
        if (rs_meta->end_version() > max_version.second) {
921
191
            max_version = rs_meta->version();
922
191
        }
923
193
    }
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 (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.push_back(rs_meta);
952
11.1k
    return Status::OK();
953
11.1k
}
954
955
11
void TabletMeta::add_rowsets_unchecked(const std::vector<RowsetSharedPtr>& to_add) {
956
34
    for (const auto& rs : to_add) {
957
34
        _rs_metas.push_back(rs->rowset_meta());
958
34
    }
959
11
}
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
    auto it = _rs_metas.begin();
965
0
    while (it != _rs_metas.end()) {
966
0
        if ((*it)->version() == version) {
967
0
            if (deleted_rs_metas != nullptr) {
968
0
                deleted_rs_metas->push_back(*it);
969
0
            }
970
0
            _rs_metas.erase(it);
971
0
            if (_enable_unique_key_merge_on_write) {
972
0
                rowset_cache_version_size =
973
0
                        _delete_bitmap->remove_rowset_cache_version((*it)->rowset_id());
974
0
            }
975
0
            return;
976
0
        } else {
977
0
            ++it;
978
0
        }
979
0
    }
980
0
    _check_mow_rowset_cache_version_size(rowset_cache_version_size);
981
0
}
982
983
void TabletMeta::modify_rs_metas(const std::vector<RowsetMetaSharedPtr>& to_add,
984
                                 const std::vector<RowsetMetaSharedPtr>& to_delete,
985
25
                                 bool same_version) {
986
25
    size_t rowset_cache_version_size = 0;
987
    // Remove to_delete rowsets from _rs_metas
988
38
    for (auto rs_to_del : to_delete) {
989
38
        auto it = _rs_metas.begin();
990
200
        while (it != _rs_metas.end()) {
991
200
            if (rs_to_del->version() == (*it)->version()) {
992
38
                _rs_metas.erase(it);
993
38
                if (_enable_unique_key_merge_on_write) {
994
1
                    rowset_cache_version_size =
995
1
                            _delete_bitmap->remove_rowset_cache_version((*it)->rowset_id());
996
1
                }
997
                // there should be only one rowset match the version
998
38
                break;
999
162
            } else {
1000
162
                ++it;
1001
162
            }
1002
200
        }
1003
38
    }
1004
25
    if (!same_version) {
1005
        // put to_delete rowsets in _stale_rs_metas.
1006
7
        _stale_rs_metas.insert(_stale_rs_metas.end(), to_delete.begin(), to_delete.end());
1007
7
    }
1008
1009
    // put to_add rowsets in _rs_metas.
1010
25
    _rs_metas.insert(_rs_metas.end(), to_add.begin(), to_add.end());
1011
25
    _check_mow_rowset_cache_version_size(rowset_cache_version_size);
1012
25
}
1013
1014
// Use the passing "rs_metas" to replace the rs meta in this tablet meta
1015
// Also clear the _stale_rs_metas because this tablet meta maybe copyied from
1016
// an existing tablet before. Add after revise, only the passing "rs_metas"
1017
// is needed.
1018
5
void TabletMeta::revise_rs_metas(std::vector<RowsetMetaSharedPtr>&& rs_metas) {
1019
5
    {
1020
5
        std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
1021
5
        _rs_metas = std::move(rs_metas);
1022
5
        _stale_rs_metas.clear();
1023
5
    }
1024
5
    if (_enable_unique_key_merge_on_write) {
1025
0
        _delete_bitmap->clear_rowset_cache_version();
1026
0
    }
1027
5
}
1028
1029
// This method should call after revise_rs_metas, since new rs_metas might be a subset
1030
// of original tablet, we should revise the delete_bitmap according to current rowset.
1031
//
1032
// Delete bitmap is protected by Tablet::_meta_lock, we don't need to acquire the
1033
// TabletMeta's _meta_lock
1034
1
void TabletMeta::revise_delete_bitmap_unlocked(const DeleteBitmap& delete_bitmap) {
1035
1
    _delete_bitmap = std::make_unique<DeleteBitmap>(tablet_id());
1036
2
    for (auto rs : _rs_metas) {
1037
2
        DeleteBitmap rs_bm(tablet_id());
1038
2
        delete_bitmap.subset({rs->rowset_id(), 0, 0}, {rs->rowset_id(), UINT32_MAX, INT64_MAX},
1039
2
                             &rs_bm);
1040
2
        _delete_bitmap->merge(rs_bm);
1041
2
    }
1042
1
    for (auto rs : _stale_rs_metas) {
1043
0
        DeleteBitmap rs_bm(tablet_id());
1044
0
        delete_bitmap.subset({rs->rowset_id(), 0, 0}, {rs->rowset_id(), UINT32_MAX, INT64_MAX},
1045
0
                             &rs_bm);
1046
0
        _delete_bitmap->merge(rs_bm);
1047
0
    }
1048
1
}
1049
1050
0
void TabletMeta::delete_stale_rs_meta_by_version(const Version& version) {
1051
0
    auto it = _stale_rs_metas.begin();
1052
0
    while (it != _stale_rs_metas.end()) {
1053
0
        if ((*it)->version() == version) {
1054
0
            it = _stale_rs_metas.erase(it);
1055
0
        } else {
1056
0
            it++;
1057
0
        }
1058
0
    }
1059
0
}
1060
1061
0
RowsetMetaSharedPtr TabletMeta::acquire_rs_meta_by_version(const Version& version) const {
1062
0
    for (auto it : _rs_metas) {
1063
0
        if (it->version() == version) {
1064
0
            return it;
1065
0
        }
1066
0
    }
1067
0
    return nullptr;
1068
0
}
1069
1070
8
RowsetMetaSharedPtr TabletMeta::acquire_stale_rs_meta_by_version(const Version& version) const {
1071
8
    for (auto it : _stale_rs_metas) {
1072
0
        if (it->version() == version) {
1073
0
            return it;
1074
0
        }
1075
0
    }
1076
8
    return nullptr;
1077
8
}
1078
1079
23
Status TabletMeta::set_partition_id(int64_t partition_id) {
1080
23
    if ((_partition_id > 0 && _partition_id != partition_id) || partition_id < 1) {
1081
0
        LOG(WARNING) << "cur partition id=" << _partition_id << " new partition id=" << partition_id
1082
0
                     << " not equal";
1083
0
    }
1084
23
    _partition_id = partition_id;
1085
23
    return Status::OK();
1086
23
}
1087
1088
0
void TabletMeta::clear_stale_rowset() {
1089
0
    _stale_rs_metas.clear();
1090
0
    if (_enable_unique_key_merge_on_write) {
1091
0
        _delete_bitmap->clear_rowset_cache_version();
1092
0
    }
1093
0
}
1094
1095
0
void TabletMeta::clear_rowsets() {
1096
0
    _rs_metas.clear();
1097
0
    if (_enable_unique_key_merge_on_write) {
1098
0
        _delete_bitmap->clear_rowset_cache_version();
1099
0
    }
1100
0
}
1101
1102
25
void TabletMeta::_check_mow_rowset_cache_version_size(size_t rowset_cache_version_size) {
1103
25
    if (_enable_unique_key_merge_on_write && config::enable_mow_verbose_log &&
1104
25
        rowset_cache_version_size > _rs_metas.size() + _stale_rs_metas.size()) {
1105
0
        std::stringstream ss;
1106
0
        auto rowset_ids = _delete_bitmap->get_rowset_cache_version();
1107
0
        std::set<std::string> tablet_rowset_ids;
1108
0
        {
1109
0
            std::shared_lock rlock(_meta_lock);
1110
0
            for (auto& rs_meta : _rs_metas) {
1111
0
                tablet_rowset_ids.emplace(rs_meta->rowset_id().to_string());
1112
0
            }
1113
0
            for (auto& rs_meta : _stale_rs_metas) {
1114
0
                tablet_rowset_ids.emplace(rs_meta->rowset_id().to_string());
1115
0
            }
1116
0
        }
1117
0
        for (const auto& rowset_id : rowset_ids) {
1118
0
            if (tablet_rowset_ids.find(rowset_id) == tablet_rowset_ids.end()) {
1119
0
                ss << rowset_id << ", ";
1120
0
            }
1121
0
        }
1122
        // size(rowset_cache_version) <= size(_rs_metas) + size(_stale_rs_metas) + size(_unused_rs)
1123
0
        std::string msg = fmt::format(
1124
0
                "tablet: {}, rowset_cache_version size: {}, "
1125
0
                "_rs_metas size: {}, _stale_rs_metas size: {}, delta: {}. rowset only in cache: {}",
1126
0
                _tablet_id, rowset_cache_version_size, _rs_metas.size(), _stale_rs_metas.size(),
1127
0
                rowset_cache_version_size - _rs_metas.size() - _stale_rs_metas.size(), ss.str());
1128
0
        LOG(INFO) << msg;
1129
0
    }
1130
25
}
1131
1132
3
bool operator==(const TabletMeta& a, const TabletMeta& b) {
1133
3
    if (a._table_id != b._table_id) return false;
1134
3
    if (a._index_id != b._index_id) return false;
1135
3
    if (a._partition_id != b._partition_id) return false;
1136
3
    if (a._tablet_id != b._tablet_id) return false;
1137
3
    if (a._replica_id != b._replica_id) return false;
1138
3
    if (a._schema_hash != b._schema_hash) return false;
1139
3
    if (a._shard_id != b._shard_id) return false;
1140
3
    if (a._creation_time != b._creation_time) return false;
1141
3
    if (a._cumulative_layer_point != b._cumulative_layer_point) return false;
1142
3
    if (a._tablet_uid != b._tablet_uid) return false;
1143
3
    if (a._tablet_type != b._tablet_type) return false;
1144
3
    if (a._tablet_state != b._tablet_state) return false;
1145
3
    if (*a._schema != *b._schema) return false;
1146
3
    if (a._rs_metas.size() != b._rs_metas.size()) return false;
1147
3
    for (int i = 0; i < a._rs_metas.size(); ++i) {
1148
0
        if (a._rs_metas[i] != b._rs_metas[i]) return false;
1149
0
    }
1150
3
    if (a._in_restore_mode != b._in_restore_mode) return false;
1151
3
    if (a._preferred_rowset_type != b._preferred_rowset_type) return false;
1152
3
    if (a._storage_policy_id != b._storage_policy_id) return false;
1153
3
    if (a._compaction_policy != b._compaction_policy) return false;
1154
3
    if (a._time_series_compaction_goal_size_mbytes != b._time_series_compaction_goal_size_mbytes)
1155
0
        return false;
1156
3
    if (a._time_series_compaction_file_count_threshold !=
1157
3
        b._time_series_compaction_file_count_threshold)
1158
0
        return false;
1159
3
    if (a._time_series_compaction_time_threshold_seconds !=
1160
3
        b._time_series_compaction_time_threshold_seconds)
1161
0
        return false;
1162
3
    if (a._time_series_compaction_empty_rowsets_threshold !=
1163
3
        b._time_series_compaction_empty_rowsets_threshold)
1164
0
        return false;
1165
3
    if (a._time_series_compaction_level_threshold != b._time_series_compaction_level_threshold)
1166
0
        return false;
1167
3
    return true;
1168
3
}
1169
1170
0
bool operator!=(const TabletMeta& a, const TabletMeta& b) {
1171
0
    return !(a == b);
1172
0
}
1173
1174
// We cannot just copy the underlying memory to construct a string
1175
// due to equivalent objects may have different padding bytes.
1176
// Reading padding bytes is undefined behavior, neither copy nor
1177
// placement new will help simplify the code.
1178
// Refer to C11 standards §6.2.6.1/6 and §6.7.9/21 for more info.
1179
64
static std::string agg_cache_key(int64_t tablet_id, const DeleteBitmap::BitmapKey& bmk) {
1180
64
    std::string ret(sizeof(tablet_id) + sizeof(bmk), '\0');
1181
64
    *reinterpret_cast<int64_t*>(ret.data()) = tablet_id;
1182
64
    auto t = reinterpret_cast<DeleteBitmap::BitmapKey*>(ret.data() + sizeof(tablet_id));
1183
64
    std::get<RowsetId>(*t).version = std::get<RowsetId>(bmk).version;
1184
64
    std::get<RowsetId>(*t).hi = std::get<RowsetId>(bmk).hi;
1185
64
    std::get<RowsetId>(*t).mi = std::get<RowsetId>(bmk).mi;
1186
64
    std::get<RowsetId>(*t).lo = std::get<RowsetId>(bmk).lo;
1187
64
    std::get<1>(*t) = std::get<1>(bmk);
1188
64
    std::get<2>(*t) = std::get<2>(bmk);
1189
64
    return ret;
1190
64
}
1191
1192
// decode cache key info from a agg_cache_key
1193
static void decode_agg_cache_key(const std::string& key_str, int64_t& tablet_id,
1194
0
                                 DeleteBitmap::BitmapKey& bmk) {
1195
0
    const char* ptr = key_str.data();
1196
0
    tablet_id = *reinterpret_cast<const int64_t*>(ptr);
1197
0
    ptr += sizeof(tablet_id);
1198
0
    auto* t = reinterpret_cast<DeleteBitmap::BitmapKey*>(const_cast<char*>(ptr));
1199
0
    std::get<RowsetId>(bmk).version = std::get<RowsetId>(*t).version;
1200
0
    std::get<RowsetId>(bmk).hi = std::get<RowsetId>(*t).hi;
1201
0
    std::get<RowsetId>(bmk).mi = std::get<RowsetId>(*t).mi;
1202
0
    std::get<RowsetId>(bmk).lo = std::get<RowsetId>(*t).lo;
1203
0
    std::get<1>(bmk) = std::get<1>(*t);
1204
0
    std::get<2>(bmk) = std::get<2>(*t);
1205
0
}
1206
1207
DeleteBitmapAggCache::DeleteBitmapAggCache(size_t capacity)
1208
1
        : LRUCachePolicy(CachePolicy::CacheType::DELETE_BITMAP_AGG_CACHE, capacity,
1209
1
                         LRUCacheType::SIZE, config::delete_bitmap_agg_cache_stale_sweep_time_sec,
1210
1
                         256) {}
1211
1212
190
DeleteBitmapAggCache* DeleteBitmapAggCache::instance() {
1213
190
    return ExecEnv::GetInstance()->delete_bitmap_agg_cache();
1214
190
}
1215
1216
1
DeleteBitmapAggCache* DeleteBitmapAggCache::create_instance(size_t capacity) {
1217
1
    return new DeleteBitmapAggCache(capacity);
1218
1
}
1219
1220
0
DeleteBitmap DeleteBitmapAggCache::snapshot(int64_t tablet_id) {
1221
0
    DeleteBitmap ret(tablet_id);
1222
0
    auto collector = [&](const LRUHandle* handle) {
1223
0
        auto key = handle->key().to_string();
1224
0
        int64_t key_tablet_id;
1225
0
        DeleteBitmap::BitmapKey bmk;
1226
0
        decode_agg_cache_key(key, key_tablet_id, bmk);
1227
0
        if (key_tablet_id == tablet_id) {
1228
0
            const auto& dbm = reinterpret_cast<DeleteBitmapAggCache::Value*>(handle->value)->bitmap;
1229
0
            ret.set(bmk, dbm);
1230
0
        }
1231
0
    };
1232
0
    DeleteBitmapAggCache::instance()->for_each_entry(collector);
1233
0
    return ret;
1234
0
}
1235
1236
1.08k
DeleteBitmap::DeleteBitmap(int64_t tablet_id) : _tablet_id(tablet_id) {}
1237
1238
7
DeleteBitmap::DeleteBitmap(const DeleteBitmap& o) {
1239
7
    std::shared_lock l1(o.lock);
1240
7
    delete_bitmap = o.delete_bitmap;
1241
7
    _tablet_id = o._tablet_id;
1242
7
}
1243
1244
0
DeleteBitmap& DeleteBitmap::operator=(const DeleteBitmap& o) {
1245
0
    if (this == &o) return *this;
1246
0
    if (this < &o) {
1247
0
        std::unique_lock l1(lock);
1248
0
        std::shared_lock l2(o.lock);
1249
0
        delete_bitmap = o.delete_bitmap;
1250
0
        _tablet_id = o._tablet_id;
1251
0
    } else {
1252
0
        std::shared_lock l2(o.lock);
1253
0
        std::unique_lock l1(lock);
1254
0
        delete_bitmap = o.delete_bitmap;
1255
0
        _tablet_id = o._tablet_id;
1256
0
    }
1257
0
    return *this;
1258
0
}
1259
1260
0
DeleteBitmap::DeleteBitmap(DeleteBitmap&& o) noexcept {
1261
0
    std::scoped_lock l(o.lock, o._rowset_cache_version_lock);
1262
0
    delete_bitmap = std::move(o.delete_bitmap);
1263
0
    _tablet_id = std::move(o._tablet_id);
1264
0
    o._rowset_cache_version.clear();
1265
0
}
1266
1267
0
DeleteBitmap& DeleteBitmap::operator=(DeleteBitmap&& o) noexcept {
1268
0
    if (this == &o) return *this;
1269
0
    std::scoped_lock l(lock, o.lock, o._rowset_cache_version_lock);
1270
0
    delete_bitmap = std::move(o.delete_bitmap);
1271
0
    _tablet_id = std::move(o._tablet_id);
1272
0
    o._rowset_cache_version.clear();
1273
0
    return *this;
1274
0
}
1275
1276
7
DeleteBitmap DeleteBitmap::snapshot() const {
1277
7
    std::shared_lock l(lock);
1278
7
    return DeleteBitmap(*this);
1279
7
}
1280
1281
3
DeleteBitmap DeleteBitmap::snapshot(Version version) const {
1282
    // Take snapshot first, then remove keys greater than given version.
1283
3
    DeleteBitmap snapshot = this->snapshot();
1284
3
    auto it = snapshot.delete_bitmap.begin();
1285
412
    while (it != snapshot.delete_bitmap.end()) {
1286
409
        if (std::get<2>(it->first) > version) {
1287
4
            it = snapshot.delete_bitmap.erase(it);
1288
405
        } else {
1289
405
            it++;
1290
405
        }
1291
409
    }
1292
3
    return snapshot;
1293
3
}
1294
1295
463k
void DeleteBitmap::add(const BitmapKey& bmk, uint32_t row_id) {
1296
463k
    std::lock_guard l(lock);
1297
463k
    delete_bitmap[bmk].add(row_id);
1298
463k
}
1299
1300
0
int DeleteBitmap::remove(const BitmapKey& bmk, uint32_t row_id) {
1301
0
    std::lock_guard l(lock);
1302
0
    auto it = delete_bitmap.find(bmk);
1303
0
    if (it == delete_bitmap.end()) return -1;
1304
0
    it->second.remove(row_id);
1305
0
    return 0;
1306
0
}
1307
1308
8
void DeleteBitmap::remove(const BitmapKey& start, const BitmapKey& end) {
1309
8
    std::lock_guard l(lock);
1310
107
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end();) {
1311
101
        auto& [k, _] = *it;
1312
101
        if (k >= end) {
1313
2
            break;
1314
2
        }
1315
99
        it = delete_bitmap.erase(it);
1316
99
    }
1317
8
}
1318
1319
0
void DeleteBitmap::remove(const std::vector<std::tuple<BitmapKey, BitmapKey>>& key_ranges) {
1320
0
    std::lock_guard l(lock);
1321
0
    for (auto& [start, end] : key_ranges) {
1322
0
        for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end();) {
1323
0
            auto& [k, _] = *it;
1324
0
            if (k >= end) {
1325
0
                break;
1326
0
            }
1327
0
            it = delete_bitmap.erase(it);
1328
0
        }
1329
0
    }
1330
0
}
1331
1332
6
bool DeleteBitmap::contains(const BitmapKey& bmk, uint32_t row_id) const {
1333
6
    std::shared_lock l(lock);
1334
6
    auto it = delete_bitmap.find(bmk);
1335
6
    return it != delete_bitmap.end() && it->second.contains(row_id);
1336
6
}
1337
1338
2
bool DeleteBitmap::contains_agg(const BitmapKey& bmk, uint32_t row_id) const {
1339
2
    return get_agg(bmk)->contains(row_id);
1340
2
}
1341
1342
0
bool DeleteBitmap::empty() const {
1343
0
    std::shared_lock l(lock);
1344
0
    return delete_bitmap.empty();
1345
0
}
1346
1347
63
uint64_t DeleteBitmap::cardinality() const {
1348
63
    std::shared_lock l(lock);
1349
63
    uint64_t res = 0;
1350
314
    for (auto entry : delete_bitmap) {
1351
314
        if (std::get<1>(entry.first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1352
314
            res += entry.second.cardinality();
1353
314
        }
1354
314
    }
1355
63
    return res;
1356
63
}
1357
1358
0
uint64_t DeleteBitmap::get_size() const {
1359
0
    std::shared_lock l(lock);
1360
0
    uint64_t charge = 0;
1361
0
    for (auto& [k, v] : delete_bitmap) {
1362
0
        if (std::get<1>(k) != DeleteBitmap::INVALID_SEGMENT_ID) {
1363
0
            charge += v.getSizeInBytes();
1364
0
        }
1365
0
    }
1366
0
    return charge;
1367
0
}
1368
1369
bool DeleteBitmap::contains_agg_with_cache_if_eligible(const BitmapKey& bmk,
1370
1
                                                       uint32_t row_id) const {
1371
1
    g_contains_agg_with_cache_if_eligible_total << 1;
1372
1
    int64_t start_version {0};
1373
1
    if (config::enable_mow_get_agg_by_cache) {
1374
1
        auto deleter = [&](Cache::Handle* handle) {
1375
0
            DeleteBitmapAggCache::instance()->release(handle);
1376
0
        };
1377
1
        std::unique_ptr<Cache::Handle, decltype(deleter)> dbm_handle(nullptr, deleter);
1378
1
        int64_t cached_version = 0;
1379
        // 1. try to lookup the desired key directly
1380
1
        dbm_handle.reset(DeleteBitmapAggCache::instance()->lookup(agg_cache_key(_tablet_id, bmk)));
1381
1
        if (dbm_handle != nullptr) {
1382
0
            cached_version = std::get<2>(bmk);
1383
1
        } else {
1384
            // 2. if not found, try to lookup with cached version
1385
1
            cached_version = _get_rowset_cache_version(bmk);
1386
1
            if (cached_version > 0) {
1387
0
                if (cached_version > std::get<2>(bmk)) {
1388
0
                    cached_version = 0;
1389
0
                } else {
1390
0
                    dbm_handle.reset(DeleteBitmapAggCache::instance()->lookup(agg_cache_key(
1391
0
                            _tablet_id, {std::get<0>(bmk), std::get<1>(bmk), cached_version})));
1392
0
                }
1393
0
            }
1394
1
        }
1395
1
        if (dbm_handle != nullptr) {
1396
0
            const auto& cached_dbm =
1397
0
                    reinterpret_cast<DeleteBitmapAggCache::Value*>(
1398
0
                            DeleteBitmapAggCache::instance()->value(dbm_handle.get()))
1399
0
                            ->bitmap;
1400
0
            if (cached_version == std::get<2>(bmk)) {
1401
0
                g_contains_agg_with_cache_if_eligible_full_hit << 1;
1402
0
            } else {
1403
0
                g_contains_agg_with_cache_if_eligible_partial_hit << 1;
1404
0
            }
1405
0
            if (cached_dbm.contains(row_id)) {
1406
0
                return true;
1407
0
            }
1408
0
            if (cached_version == std::get<2>(bmk)) {
1409
0
                return false;
1410
0
            }
1411
0
            start_version = cached_version + 1;
1412
0
        }
1413
1
    }
1414
1
    DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1415
1
    std::shared_lock l(lock);
1416
1
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1417
0
        auto& [k, bm] = *it;
1418
0
        if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1419
0
            std::get<2>(k) > std::get<2>(bmk)) {
1420
0
            break;
1421
0
        }
1422
0
        if (bm.contains(row_id)) {
1423
0
            return true;
1424
0
        }
1425
0
    }
1426
1
    return false;
1427
1
}
1428
1429
0
void DeleteBitmap::remove_sentinel_marks() {
1430
0
    std::lock_guard l(lock);
1431
0
    for (auto it = delete_bitmap.begin(), end = delete_bitmap.end(); it != end;) {
1432
0
        if (std::get<1>(it->first) == DeleteBitmap::INVALID_SEGMENT_ID) {
1433
0
            it = delete_bitmap.erase(it);
1434
0
        } else {
1435
0
            ++it;
1436
0
        }
1437
0
    }
1438
0
}
1439
1440
38
int DeleteBitmap::set(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1441
38
    std::lock_guard l(lock);
1442
38
    auto [_, inserted] = delete_bitmap.insert_or_assign(bmk, segment_delete_bitmap);
1443
38
    return inserted;
1444
38
}
1445
1446
7
int DeleteBitmap::get(const BitmapKey& bmk, roaring::Roaring* segment_delete_bitmap) const {
1447
7
    std::shared_lock l(lock);
1448
7
    auto it = delete_bitmap.find(bmk);
1449
7
    if (it == delete_bitmap.end()) return -1;
1450
7
    *segment_delete_bitmap = it->second; // copy
1451
7
    return 0;
1452
7
}
1453
1454
54
const roaring::Roaring* DeleteBitmap::get(const BitmapKey& bmk) const {
1455
54
    std::shared_lock l(lock);
1456
54
    auto it = delete_bitmap.find(bmk);
1457
54
    if (it == delete_bitmap.end()) return nullptr;
1458
41
    return &(it->second); // get address
1459
54
}
1460
1461
void DeleteBitmap::subset(const BitmapKey& start, const BitmapKey& end,
1462
3
                          DeleteBitmap* subset_rowset_map) const {
1463
3
    DCHECK(start < end);
1464
3
    std::shared_lock l(lock);
1465
26
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1466
25
        auto& [k, bm] = *it;
1467
25
        if (k >= end) {
1468
2
            break;
1469
2
        }
1470
23
        subset_rowset_map->set(k, bm);
1471
23
    }
1472
3
}
1473
1474
void DeleteBitmap::subset(std::vector<std::pair<RowsetId, int64_t>>& rowset_ids,
1475
                          int64_t start_version, int64_t end_version,
1476
0
                          DeleteBitmap* subset_delete_map) const {
1477
0
    DCHECK(start_version <= end_version);
1478
0
    for (auto& [rowset_id, _] : rowset_ids) {
1479
0
        BitmapKey start {rowset_id, 0, 0};
1480
0
        BitmapKey end {rowset_id, UINT32_MAX, end_version + 1};
1481
0
        std::shared_lock l(lock);
1482
0
        for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1483
0
            auto& [k, bm] = *it;
1484
0
            if (k >= end) {
1485
0
                break;
1486
0
            }
1487
0
            auto version = std::get<2>(k);
1488
0
            if (version >= start_version && version <= end_version) {
1489
0
                subset_delete_map->merge(k, bm);
1490
0
                VLOG_DEBUG << "subset delete bitmap, tablet=" << _tablet_id << ", version=["
1491
0
                           << start_version << ", " << end_version
1492
0
                           << "]. rowset=" << std::get<0>(k).to_string()
1493
0
                           << ", segment=" << std::get<1>(k) << ", version=" << version
1494
0
                           << ", cardinality=" << bm.cardinality();
1495
0
            }
1496
0
        }
1497
0
    }
1498
0
}
1499
1500
void DeleteBitmap::subset_and_agg(std::vector<std::pair<RowsetId, int64_t>>& rowset_ids,
1501
                                  int64_t start_version, int64_t end_version,
1502
1
                                  DeleteBitmap* subset_delete_map) const {
1503
1
    DCHECK(start_version <= end_version);
1504
2
    for (auto& [rowset_id, segment_num] : rowset_ids) {
1505
6
        for (int64_t seg_id = 0; seg_id < segment_num; ++seg_id) {
1506
4
            BitmapKey end {rowset_id, seg_id, end_version};
1507
4
            auto bm = get_agg_without_cache(end, start_version);
1508
4
            VLOG_DEBUG << "subset delete bitmap, tablet=" << _tablet_id << ", rowset=" << rowset_id
1509
0
                       << ", segment=" << seg_id << ", version=[" << start_version << "-"
1510
0
                       << end_version << "], cardinality=" << bm->cardinality();
1511
4
            if (bm->isEmpty()) {
1512
0
                continue;
1513
0
            }
1514
4
            subset_delete_map->merge(end, *bm);
1515
4
        }
1516
2
    }
1517
1
}
1518
1519
0
size_t DeleteBitmap::get_count_with_range(const BitmapKey& start, const BitmapKey& end) const {
1520
0
    DCHECK(start < end);
1521
0
    size_t count = 0;
1522
0
    std::shared_lock l(lock);
1523
0
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1524
0
        auto& [k, bm] = *it;
1525
0
        if (k >= end) {
1526
0
            break;
1527
0
        }
1528
0
        count++;
1529
0
    }
1530
0
    return count;
1531
0
}
1532
1533
6
void DeleteBitmap::merge(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1534
6
    std::lock_guard l(lock);
1535
6
    auto [iter, succ] = delete_bitmap.emplace(bmk, segment_delete_bitmap);
1536
6
    if (!succ) {
1537
0
        iter->second |= segment_delete_bitmap;
1538
0
    }
1539
6
}
1540
1541
9
void DeleteBitmap::merge(const DeleteBitmap& other) {
1542
9
    std::lock_guard l(lock);
1543
29
    for (auto& i : other.delete_bitmap) {
1544
29
        auto [j, succ] = this->delete_bitmap.insert(i);
1545
29
        if (!succ) j->second |= i.second;
1546
29
    }
1547
9
}
1548
1549
63
uint64_t DeleteBitmap::get_delete_bitmap_count() {
1550
63
    std::shared_lock l(lock);
1551
63
    uint64_t count = 0;
1552
377
    for (auto it = delete_bitmap.begin(); it != delete_bitmap.end(); it++) {
1553
314
        if (std::get<1>(it->first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1554
314
            count++;
1555
314
        }
1556
314
    }
1557
63
    return count;
1558
63
}
1559
1560
void DeleteBitmap::traverse_rowset_and_version(
1561
0
        const std::function<int(const RowsetId& rowsetId, int64_t version)>& func) const {
1562
0
    std::shared_lock l(lock);
1563
0
    auto it = delete_bitmap.cbegin();
1564
0
    while (it != delete_bitmap.cend()) {
1565
0
        RowsetId rowset_id = std::get<0>(it->first);
1566
0
        int64_t version = std::get<2>(it->first);
1567
0
        int result = func(rowset_id, version);
1568
0
        if (result == -2) {
1569
            // find next <rowset, version>
1570
0
            it++;
1571
0
        } else {
1572
            // find next <rowset>
1573
0
            it = delete_bitmap.upper_bound({rowset_id, std::numeric_limits<SegmentId>::max(),
1574
0
                                            std::numeric_limits<Version>::max()});
1575
0
        }
1576
0
    }
1577
0
}
1578
1579
0
bool DeleteBitmap::has_calculated_for_multi_segments(const RowsetId& rowset_id) const {
1580
0
    return contains({rowset_id, INVALID_SEGMENT_ID, TEMP_VERSION_COMMON}, ROWSET_SENTINEL_MARK);
1581
0
}
1582
1583
1
size_t DeleteBitmap::remove_rowset_cache_version(const RowsetId& rowset_id) {
1584
1
    std::lock_guard l(_rowset_cache_version_lock);
1585
1
    _rowset_cache_version.erase(rowset_id);
1586
1
    VLOG_DEBUG << "remove agg cache version for tablet=" << _tablet_id
1587
0
               << ", rowset=" << rowset_id.to_string();
1588
1
    return _rowset_cache_version.size();
1589
1
}
1590
1591
0
void DeleteBitmap::clear_rowset_cache_version() {
1592
0
    std::lock_guard l(_rowset_cache_version_lock);
1593
0
    _rowset_cache_version.clear();
1594
0
    VLOG_DEBUG << "clear agg cache version for tablet=" << _tablet_id;
1595
0
}
1596
1597
0
std::set<std::string> DeleteBitmap::get_rowset_cache_version() {
1598
0
    std::set<std::string> set;
1599
0
    std::shared_lock l(_rowset_cache_version_lock);
1600
0
    for (auto& [k, _] : _rowset_cache_version) {
1601
0
        set.insert(k.to_string());
1602
0
    }
1603
0
    return set;
1604
0
}
1605
1606
49
DeleteBitmap::Version DeleteBitmap::_get_rowset_cache_version(const BitmapKey& bmk) const {
1607
49
    std::shared_lock l(_rowset_cache_version_lock);
1608
49
    if (auto it = _rowset_cache_version.find(std::get<0>(bmk)); it != _rowset_cache_version.end()) {
1609
39
        auto& segment_cache_version = it->second;
1610
39
        if (auto it1 = segment_cache_version.find(std::get<1>(bmk));
1611
39
            it1 != segment_cache_version.end()) {
1612
10
            return it1->second;
1613
10
        }
1614
39
    }
1615
39
    return 0;
1616
49
}
1617
1618
0
DeleteBitmap DeleteBitmap::agg_cache_snapshot() {
1619
0
    return DeleteBitmapAggCache::instance()->snapshot(_tablet_id);
1620
0
}
1621
1622
969
void DeleteBitmap::set_tablet_id(int64_t tablet_id) {
1623
969
    _tablet_id = tablet_id;
1624
969
}
1625
1626
54
std::shared_ptr<roaring::Roaring> DeleteBitmap::get_agg(const BitmapKey& bmk) const {
1627
54
    std::string key_str = agg_cache_key(_tablet_id, bmk); // Cache key container
1628
54
    CacheKey key(key_str);
1629
54
    Cache::Handle* handle = DeleteBitmapAggCache::instance()->lookup(key);
1630
1631
54
    DeleteBitmapAggCache::Value* val =
1632
54
            handle == nullptr ? nullptr
1633
54
                              : reinterpret_cast<DeleteBitmapAggCache::Value*>(
1634
6
                                        DeleteBitmapAggCache::instance()->value(handle));
1635
    // FIXME: do we need a mutex here to get rid of duplicated initializations
1636
    //        of cache entries in some cases?
1637
54
    if (val == nullptr) { // Renew if needed, put a new Value to cache
1638
48
        val = new DeleteBitmapAggCache::Value();
1639
48
        Version start_version =
1640
48
                config::enable_mow_get_agg_by_cache ? _get_rowset_cache_version(bmk) : 0;
1641
48
        if (start_version > 0) {
1642
9
            Cache::Handle* handle2 = DeleteBitmapAggCache::instance()->lookup(
1643
9
                    agg_cache_key(_tablet_id, {std::get<0>(bmk), std::get<1>(bmk), start_version}));
1644
1645
9
            DBUG_EXECUTE_IF("DeleteBitmap::get_agg.cache_miss", {
1646
9
                if (handle2 != nullptr) {
1647
9
                    auto p = dp->param("percent", 0.3);
1648
9
                    std::mt19937 gen {std::random_device {}()};
1649
9
                    std::bernoulli_distribution inject_fault {p};
1650
9
                    if (inject_fault(gen)) {
1651
9
                        LOG_INFO("injection DeleteBitmap::get_agg.cache_miss, tablet_id={}",
1652
9
                                 _tablet_id);
1653
9
                        handle2 = nullptr;
1654
9
                    }
1655
9
                }
1656
9
            });
1657
9
            if (handle2 == nullptr || start_version > std::get<2>(bmk)) {
1658
0
                start_version = 0;
1659
9
            } else {
1660
9
                val->bitmap |= reinterpret_cast<DeleteBitmapAggCache::Value*>(
1661
9
                                       DeleteBitmapAggCache::instance()->value(handle2))
1662
9
                                       ->bitmap;
1663
9
                VLOG_DEBUG << "get agg cache version=" << start_version
1664
0
                           << " for tablet=" << _tablet_id
1665
0
                           << ", rowset=" << std::get<0>(bmk).to_string()
1666
0
                           << ", segment=" << std::get<1>(bmk);
1667
9
                start_version += 1;
1668
9
            }
1669
9
            if (handle2 != nullptr) {
1670
9
                DeleteBitmapAggCache::instance()->release(handle2);
1671
9
            }
1672
9
        }
1673
48
        {
1674
48
            std::shared_lock l(lock);
1675
48
            DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1676
87
            for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1677
84
                auto& [k, bm] = *it;
1678
84
                if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1679
84
                    std::get<2>(k) > std::get<2>(bmk)) {
1680
45
                    break;
1681
45
                }
1682
39
                val->bitmap |= bm;
1683
39
            }
1684
48
        }
1685
48
        size_t charge = val->bitmap.getSizeInBytes() + sizeof(DeleteBitmapAggCache::Value);
1686
48
        handle = DeleteBitmapAggCache::instance()->insert(key, val, charge, charge,
1687
48
                                                          CachePriority::NORMAL);
1688
48
        if (config::enable_mow_get_agg_by_cache && !val->bitmap.isEmpty()) {
1689
37
            std::lock_guard l(_rowset_cache_version_lock);
1690
            // this version is already agg
1691
37
            _rowset_cache_version[std::get<0>(bmk)][std::get<1>(bmk)] = std::get<2>(bmk);
1692
37
            VLOG_DEBUG << "set agg cache version=" << std::get<2>(bmk)
1693
0
                       << " for tablet=" << _tablet_id
1694
0
                       << ", rowset=" << std::get<0>(bmk).to_string()
1695
0
                       << ", segment=" << std::get<1>(bmk);
1696
37
        }
1697
48
        if (start_version > 0 && config::enable_mow_get_agg_correctness_check_core) {
1698
0
            std::shared_ptr<roaring::Roaring> bitmap = get_agg_without_cache(bmk);
1699
0
            if (val->bitmap != *bitmap) {
1700
0
                CHECK(false) << ". get agg correctness check failed for tablet=" << _tablet_id
1701
0
                             << ", rowset=" << std::get<0>(bmk).to_string()
1702
0
                             << ", segment=" << std::get<1>(bmk) << ", version=" << std::get<2>(bmk)
1703
0
                             << ". start_version from cache=" << start_version
1704
0
                             << ", delete_bitmap cardinality with cache="
1705
0
                             << val->bitmap.cardinality()
1706
0
                             << ", delete_bitmap cardinality without cache="
1707
0
                             << bitmap->cardinality();
1708
0
            }
1709
0
        }
1710
48
    }
1711
1712
    // It is natural for the cache to reclaim the underlying memory
1713
54
    return std::shared_ptr<roaring::Roaring>(
1714
54
            &val->bitmap, [handle](...) { DeleteBitmapAggCache::instance()->release(handle); });
1715
54
}
1716
1717
std::shared_ptr<roaring::Roaring> DeleteBitmap::get_agg_without_cache(
1718
4
        const BitmapKey& bmk, const int64_t start_version) const {
1719
4
    std::shared_ptr<roaring::Roaring> bitmap = std::make_shared<roaring::Roaring>();
1720
4
    std::shared_lock l(lock);
1721
4
    DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), start_version};
1722
24
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1723
23
        auto& [k, bm] = *it;
1724
23
        if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1725
23
            std::get<2>(k) > std::get<2>(bmk)) {
1726
3
            break;
1727
3
        }
1728
20
        *bitmap |= bm;
1729
20
    }
1730
4
    return bitmap;
1731
4
}
1732
1733
0
std::string tablet_state_name(TabletState state) {
1734
0
    switch (state) {
1735
0
    case TABLET_NOTREADY:
1736
0
        return "TABLET_NOTREADY";
1737
1738
0
    case TABLET_RUNNING:
1739
0
        return "TABLET_RUNNING";
1740
1741
0
    case TABLET_TOMBSTONED:
1742
0
        return "TABLET_TOMBSTONED";
1743
1744
0
    case TABLET_STOPPED:
1745
0
        return "TABLET_STOPPED";
1746
1747
0
    case TABLET_SHUTDOWN:
1748
0
        return "TABLET_SHUTDOWN";
1749
1750
0
    default:
1751
0
        return "TabletState(" + std::to_string(state) + ")";
1752
0
    }
1753
0
}
1754
1755
#include "common/compile_check_end.h"
1756
} // namespace doris