Coverage Report

Created: 2025-08-18 03:01

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