Coverage Report

Created: 2026-08-04 13:44

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