Coverage Report

Created: 2026-06-13 22:56

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