Coverage Report

Created: 2026-07-27 16:12

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