Coverage Report

Created: 2026-05-29 12:23

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