Coverage Report

Created: 2025-12-11 01:17

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