Coverage Report

Created: 2026-07-08 14:26

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