Coverage Report

Created: 2026-06-18 11:49

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