Coverage Report

Created: 2026-04-25 11:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/rowset/rowset_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/rowset/rowset_meta.h"
19
20
#include <gen_cpp/olap_file.pb.h>
21
#include <glog/logging.h>
22
23
#include <memory>
24
#include <random>
25
26
#include "cloud/cloud_storage_engine.h"
27
#include "common/logging.h"
28
#include "common/status.h"
29
#include "cpp/sync_point.h"
30
#include "exec/common/variant_util.h"
31
#include "google/protobuf/util/message_differencer.h"
32
#include "io/fs/encrypted_fs_factory.h"
33
#include "io/fs/file_system.h"
34
#include "io/fs/file_writer.h"
35
#include "io/fs/local_file_system.h"
36
#include "io/fs/packed_file_manager.h"
37
#include "io/fs/packed_file_system.h"
38
#include "json2pb/json_to_pb.h"
39
#include "json2pb/pb_to_json.h"
40
#include "runtime/exec_env.h"
41
#include "storage/olap_common.h"
42
#include "storage/storage_policy.h"
43
#include "storage/tablet/base_tablet.h"
44
#include "storage/tablet/tablet_fwd.h"
45
#include "storage/tablet/tablet_schema.h"
46
#include "storage/tablet/tablet_schema_cache.h"
47
#include "util/lru_cache.h"
48
49
namespace doris {
50
51
480k
RowsetMeta::~RowsetMeta() {
52
480k
    if (_handle) {
53
456k
        TabletSchemaCache::instance()->release(_handle);
54
456k
    }
55
480k
}
56
57
21.5k
bool RowsetMeta::init(std::string_view pb_rowset_meta) {
58
21.5k
    bool ret = _deserialize_from_pb(pb_rowset_meta);
59
21.5k
    if (!ret) {
60
1
        return false;
61
1
    }
62
21.4k
    _init();
63
21.4k
    return true;
64
21.5k
}
65
66
21.2k
bool RowsetMeta::init(const RowsetMeta* rowset_meta) {
67
21.2k
    RowsetMetaPB rowset_meta_pb;
68
21.2k
    rowset_meta->to_rowset_pb(&rowset_meta_pb);
69
21.2k
    return init_from_pb(rowset_meta_pb);
70
21.2k
}
71
72
681k
bool RowsetMeta::init_from_pb(const RowsetMetaPB& rowset_meta_pb) {
73
681k
    if (rowset_meta_pb.has_tablet_schema()) {
74
667k
        set_tablet_schema(rowset_meta_pb.tablet_schema());
75
667k
    }
76
    // Release ownership of TabletSchemaPB from `rowset_meta_pb` and then set it back to `rowset_meta_pb`,
77
    // this won't break const semantics of `rowset_meta_pb`, because `rowset_meta_pb` is not changed
78
    // before and after call this method.
79
681k
    auto& mut_rowset_meta_pb = const_cast<RowsetMetaPB&>(rowset_meta_pb);
80
681k
    auto* schema = mut_rowset_meta_pb.release_tablet_schema();
81
681k
    _rowset_meta_pb = mut_rowset_meta_pb;
82
681k
    mut_rowset_meta_pb.set_allocated_tablet_schema(schema);
83
681k
    _init();
84
681k
    return true;
85
681k
}
86
87
61
bool RowsetMeta::init_from_json(const std::string& json_rowset_meta) {
88
61
    bool ret = json2pb::JsonToProtoMessage(json_rowset_meta, &_rowset_meta_pb);
89
61
    if (!ret) {
90
1
        return false;
91
1
    }
92
60
    _init();
93
60
    return true;
94
61
}
95
96
0
bool RowsetMeta::json_rowset_meta(std::string* json_rowset_meta) {
97
0
    json2pb::Pb2JsonOptions json_options;
98
0
    json_options.pretty_json = true;
99
0
    bool ret = json2pb::ProtoMessageToJson(_rowset_meta_pb, json_rowset_meta, json_options);
100
0
    return ret;
101
0
}
102
103
804k
io::FileSystemSPtr RowsetMeta::physical_fs() {
104
804k
    if (is_local()) {
105
573k
        return io::global_local_filesystem();
106
573k
    }
107
108
230k
    auto storage_resource = remote_storage_resource();
109
230k
    if (storage_resource) {
110
230k
        return storage_resource.value()->fs;
111
18.4E
    } else {
112
18.4E
        LOG(WARNING) << storage_resource.error();
113
18.4E
        return nullptr;
114
18.4E
    }
115
230k
}
116
117
798k
io::FileSystemSPtr RowsetMeta::fs() {
118
798k
    auto fs = physical_fs();
119
120
798k
#ifndef BE_TEST
121
798k
    auto algorithm = _determine_encryption_once.call([this]() -> Result<EncryptionAlgorithmPB> {
122
58.3k
        auto maybe_tablet = ExecEnv::get_tablet(tablet_id());
123
58.3k
        if (!maybe_tablet) {
124
0
            LOG(WARNING) << "get tablet failed: " << maybe_tablet.error();
125
0
            return ResultError(maybe_tablet.error());
126
0
        }
127
58.3k
        auto tablet = maybe_tablet.value();
128
58.3k
        return tablet->tablet_meta()->encryption_algorithm();
129
58.3k
    });
130
798k
    if (!algorithm.has_value()) {
131
        // TODO: return a Result<FileSystemSPtr> in this method?
132
0
        return nullptr;
133
0
    }
134
135
    // Apply packed file system first if enabled and index_map is not empty
136
798k
    io::FileSystemSPtr wrapped = fs;
137
798k
    if (_rowset_meta_pb.packed_slice_locations_size() > 0) {
138
0
        std::unordered_map<std::string, io::PackedSliceLocation> index_map;
139
0
        for (const auto& [path, index_pb] : _rowset_meta_pb.packed_slice_locations()) {
140
0
            io::PackedSliceLocation index;
141
0
            index.packed_file_path = index_pb.packed_file_path();
142
0
            index.offset = index_pb.offset();
143
0
            index.size = index_pb.size();
144
0
            index.packed_file_size =
145
0
                    index_pb.has_packed_file_size() ? index_pb.packed_file_size() : -1;
146
0
            index.tablet_id = tablet_id();
147
0
            index.rowset_id = _rowset_id.to_string();
148
0
            index.resource_id = wrapped->id();
149
0
            index_map[path] = index;
150
0
        }
151
0
        if (!index_map.empty()) {
152
0
            io::PackedAppendContext append_info;
153
0
            append_info.tablet_id = tablet_id();
154
0
            append_info.rowset_id = _rowset_id.to_string();
155
0
            append_info.txn_id = txn_id();
156
0
            wrapped = std::make_shared<io::PackedFileSystem>(wrapped, index_map, append_info);
157
0
        }
158
0
    }
159
160
    // Then apply encryption on top
161
798k
    wrapped = io::make_file_system(wrapped, algorithm.value());
162
798k
    return wrapped;
163
#else
164
    return fs;
165
#endif
166
798k
}
167
168
555k
Result<const StorageResource*> RowsetMeta::remote_storage_resource() {
169
555k
    if (is_local()) {
170
0
        return ResultError(Status::InternalError(
171
0
                "local rowset has no storage resource. tablet_id={} rowset_id={}", tablet_id(),
172
0
                _rowset_id.to_string()));
173
0
    }
174
175
555k
    if (!_storage_resource.fs) {
176
21.3k
        if (auto storage_resource = get_storage_resource(resource_id())) {
177
21.3k
            _storage_resource = std::move(storage_resource->first);
178
21.3k
        } else {
179
50
            if (config::is_cloud_mode()) {
180
                // When creating a new cluster or creating a storage resource, BE may not sync storage resource,
181
                // at the moment a query is coming, the BetaRowsetReader call loadSegment and use this method
182
                // to get the storage resource, so we need to sync storage resource here.
183
50
                ExecEnv::GetInstance()->storage_engine().to_cloud().sync_storage_vault();
184
50
                if (auto retry_resource = get_storage_resource(resource_id())) {
185
0
                    _storage_resource = std::move(retry_resource->first);
186
0
                    return &_storage_resource;
187
0
                }
188
50
            }
189
39
            return ResultError(Status::InternalError("cannot find storage resource. resource_id={}",
190
39
                                                     resource_id()));
191
39
        }
192
21.3k
    }
193
555k
    return &_storage_resource;
194
555k
}
195
196
194k
void RowsetMeta::set_remote_storage_resource(StorageResource resource) {
197
194k
    _storage_resource = std::move(resource);
198
194k
    _rowset_meta_pb.set_resource_id(_storage_resource.fs->id());
199
194k
}
200
201
680k
bool RowsetMeta::has_variant_type_in_schema() const {
202
680k
    return _schema && _schema->num_variant_columns() > 0;
203
680k
}
204
205
683k
void RowsetMeta::to_rowset_pb(RowsetMetaPB* rs_meta_pb, bool skip_schema) const {
206
683k
    *rs_meta_pb = _rowset_meta_pb;
207
683k
    if (_schema) [[likely]] {
208
660k
        rs_meta_pb->set_schema_version(_schema->schema_version());
209
660k
        if (!skip_schema) {
210
            // For cloud, separate tablet schema from rowset meta to reduce persistent size.
211
409k
            _schema->to_schema_pb(rs_meta_pb->mutable_tablet_schema());
212
409k
        }
213
660k
    }
214
683k
    rs_meta_pb->set_has_variant_type_in_schema(has_variant_type_in_schema());
215
683k
}
216
217
491k
RowsetMetaPB RowsetMeta::get_rowset_pb(bool skip_schema) const {
218
491k
    RowsetMetaPB rowset_meta_pb;
219
491k
    to_rowset_pb(&rowset_meta_pb, skip_schema);
220
491k
    return rowset_meta_pb;
221
491k
}
222
223
446k
void RowsetMeta::set_tablet_schema(const TabletSchemaSPtr& tablet_schema) {
224
446k
    if (_handle) {
225
222k
        TabletSchemaCache::instance()->release(_handle);
226
222k
    }
227
446k
    auto pair = TabletSchemaCache::instance()->insert(tablet_schema->to_key());
228
446k
    _handle = pair.first;
229
446k
    _schema = pair.second;
230
446k
}
231
232
688k
void RowsetMeta::set_tablet_schema(const TabletSchemaPB& tablet_schema) {
233
688k
    if (_handle) {
234
0
        TabletSchemaCache::instance()->release(_handle);
235
0
    }
236
688k
    auto pair = TabletSchemaCache::instance()->insert(
237
688k
            TabletSchema::deterministic_string_serialize(tablet_schema));
238
688k
    _handle = pair.first;
239
688k
    _schema = pair.second;
240
688k
}
241
242
21.5k
bool RowsetMeta::_deserialize_from_pb(std::string_view value) {
243
21.5k
    if (!_rowset_meta_pb.ParseFromArray(value.data(), cast_set<int32_t>(value.size()))) {
244
1
        _rowset_meta_pb.Clear();
245
1
        return false;
246
1
    }
247
21.4k
    if (_rowset_meta_pb.has_tablet_schema()) {
248
21.4k
        set_tablet_schema(_rowset_meta_pb.tablet_schema());
249
21.4k
        _rowset_meta_pb.set_allocated_tablet_schema(nullptr);
250
21.4k
    }
251
21.4k
    return true;
252
21.5k
}
253
254
0
bool RowsetMeta::_serialize_to_pb(std::string* value) {
255
0
    if (value == nullptr) {
256
0
        return false;
257
0
    }
258
0
    RowsetMetaPB rowset_meta_pb = _rowset_meta_pb;
259
0
    if (_schema) {
260
0
        _schema->to_schema_pb(rowset_meta_pb.mutable_tablet_schema());
261
0
    }
262
0
    return rowset_meta_pb.SerializeToString(value);
263
0
}
264
265
703k
void RowsetMeta::_init() {
266
703k
    if (_rowset_meta_pb.rowset_id() > 0) {
267
3.57k
        _rowset_id.init(_rowset_meta_pb.rowset_id());
268
699k
    } else {
269
699k
        _rowset_id.init(_rowset_meta_pb.rowset_id_v2());
270
699k
    }
271
703k
    update_metadata_size();
272
703k
}
273
274
197k
void RowsetMeta::add_segments_file_size(const std::vector<size_t>& seg_file_size) {
275
197k
    _rowset_meta_pb.set_enable_segments_file_size(true);
276
197k
    for (auto fsize : seg_file_size) {
277
62.2k
        _rowset_meta_pb.add_segments_file_size(fsize);
278
62.2k
    }
279
197k
}
280
281
931k
int64_t RowsetMeta::segment_file_size(int seg_id) const {
282
18.4E
    DCHECK(_rowset_meta_pb.segments_file_size().empty() ||
283
18.4E
           _rowset_meta_pb.segments_file_size_size() > seg_id)
284
18.4E
            << _rowset_meta_pb.segments_file_size_size() << ' ' << seg_id;
285
931k
    return _rowset_meta_pb.enable_segments_file_size()
286
931k
                   ? (_rowset_meta_pb.segments_file_size_size() > seg_id
287
344k
                              ? _rowset_meta_pb.segments_file_size(seg_id)
288
18.4E
                              : -1)
289
931k
                   : -1;
290
931k
}
291
292
void RowsetMeta::set_segments_key_bounds(const std::vector<KeyBoundsPB>& segments_key_bounds,
293
244k
                                         bool aggregate_into_single) {
294
244k
    _rowset_meta_pb.clear_segments_key_bounds();
295
244k
    bool did_aggregate = aggregate_into_single && !segments_key_bounds.empty();
296
244k
    if (did_aggregate) {
297
41.8k
        const std::string* overall_min = &segments_key_bounds.front().min_key();
298
41.8k
        const std::string* overall_max = &segments_key_bounds.front().max_key();
299
43.8k
        for (const KeyBoundsPB& key_bounds : segments_key_bounds) {
300
43.8k
            if (key_bounds.min_key() < *overall_min) {
301
4
                overall_min = &key_bounds.min_key();
302
4
            }
303
43.8k
            if (key_bounds.max_key() > *overall_max) {
304
1.39k
                overall_max = &key_bounds.max_key();
305
1.39k
            }
306
43.8k
        }
307
41.8k
        KeyBoundsPB* aggregated = _rowset_meta_pb.add_segments_key_bounds();
308
41.8k
        aggregated->set_min_key(*overall_min);
309
41.8k
        aggregated->set_max_key(*overall_max);
310
202k
    } else {
311
202k
        for (const KeyBoundsPB& key_bounds : segments_key_bounds) {
312
47.6k
            KeyBoundsPB* new_key_bounds = _rowset_meta_pb.add_segments_key_bounds();
313
47.6k
            *new_key_bounds = key_bounds;
314
47.6k
        }
315
202k
    }
316
244k
    set_segments_key_bounds_aggregated(did_aggregate);
317
318
244k
    int32_t truncation_threshold = config::segments_key_bounds_truncation_threshold;
319
244k
    if (config::random_segments_key_bounds_truncation) {
320
0
        std::mt19937 generator(std::random_device {}());
321
0
        std::uniform_int_distribution<int> distribution(-10, 40);
322
0
        truncation_threshold = distribution(generator);
323
0
    }
324
244k
    bool really_do_truncation {false};
325
244k
    if (truncation_threshold > 0) {
326
244k
        for (auto& segment_key_bounds : *_rowset_meta_pb.mutable_segments_key_bounds()) {
327
89.2k
            if (segment_key_bounds.min_key().size() > truncation_threshold) {
328
51.9k
                really_do_truncation = true;
329
51.9k
                segment_key_bounds.mutable_min_key()->resize(truncation_threshold);
330
51.9k
            }
331
89.2k
            if (segment_key_bounds.max_key().size() > truncation_threshold) {
332
52.1k
                really_do_truncation = true;
333
52.1k
                segment_key_bounds.mutable_max_key()->resize(truncation_threshold);
334
52.1k
            }
335
89.2k
        }
336
244k
    }
337
244k
    set_segments_key_bounds_truncated(really_do_truncation || is_segments_key_bounds_truncated());
338
244k
}
339
340
3.58k
void RowsetMeta::merge_rowset_meta(const RowsetMeta& other) {
341
3.58k
    set_num_segments(num_segments() + other.num_segments());
342
3.58k
    set_num_rows(num_rows() + other.num_rows());
343
3.58k
    set_data_disk_size(data_disk_size() + other.data_disk_size());
344
3.58k
    set_total_disk_size(total_disk_size() + other.total_disk_size());
345
3.58k
    set_index_disk_size(index_disk_size() + other.index_disk_size());
346
3.58k
    set_total_disk_size(data_disk_size() + index_disk_size());
347
3.58k
    set_segments_key_bounds_truncated(is_segments_key_bounds_truncated() ||
348
3.58k
                                      other.is_segments_key_bounds_truncated());
349
    // merge_rowset_meta is used in the MOW partial-update publish path, which relies
350
    // on per-segment bounds. Aggregation should never be enabled for MOW rowsets,
351
    // so we do not expect either side to be aggregated here.
352
18.4E
    DCHECK(!is_segments_key_bounds_aggregated() && !other.is_segments_key_bounds_aggregated())
353
18.4E
            << "merge_rowset_meta encountered aggregated key bounds";
354
3.58k
    if (_rowset_meta_pb.num_segment_rows_size() > 0) {
355
1.57k
        if (other.num_segments() > 0) {
356
19
            if (other._rowset_meta_pb.num_segment_rows_size() > 0) {
357
19
                for (auto row_count : other._rowset_meta_pb.num_segment_rows()) {
358
19
                    _rowset_meta_pb.add_num_segment_rows(row_count);
359
19
                }
360
19
            } else {
361
                // This may happen when a partial update load commits in high version doirs_be
362
                // and publishes with new segments in low version doris_be. In this case, just clear
363
                // all num_segment_rows.
364
0
                _rowset_meta_pb.clear_num_segment_rows();
365
0
            }
366
19
        }
367
1.57k
    }
368
3.58k
    for (auto&& key_bound : other.get_segments_key_bounds()) {
369
19
        add_segment_key_bounds(key_bound);
370
19
    }
371
3.58k
    if (_rowset_meta_pb.enable_segments_file_size() &&
372
3.58k
        other._rowset_meta_pb.enable_segments_file_size()) {
373
3.36k
        for (auto fsize : other.segments_file_size()) {
374
19
            _rowset_meta_pb.add_segments_file_size(fsize);
375
19
        }
376
3.36k
    }
377
3.58k
    if (_rowset_meta_pb.enable_inverted_index_file_info() &&
378
3.58k
        other._rowset_meta_pb.enable_inverted_index_file_info()) {
379
191
        for (auto finfo : other.inverted_index_file_info()) {
380
0
            InvertedIndexFileInfo* new_file_info = _rowset_meta_pb.add_inverted_index_file_info();
381
0
            *new_file_info = finfo;
382
0
        }
383
191
    }
384
    // In partial update the rowset schema maybe updated when table contains variant type, so we need the newest schema to be updated
385
    // Otherwise the schema is stale and lead to wrong data read
386
3.58k
    TEST_SYNC_POINT_RETURN_WITH_VOID("RowsetMeta::merge_rowset_meta:skip_schema_merge");
387
3.58k
    if (tablet_schema()->num_variant_columns() > 0) {
388
        // merge extracted columns
389
109
        TabletSchemaSPtr merged_schema;
390
109
        static_cast<void>(variant_util::get_least_common_schema(
391
109
                {tablet_schema(), other.tablet_schema()}, nullptr, merged_schema));
392
109
        if (*_schema != *merged_schema) {
393
0
            set_tablet_schema(merged_schema);
394
0
        }
395
109
    }
396
3.58k
    if (rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
397
3.31k
        set_rowset_state(RowsetStatePB::COMMITTED);
398
3.31k
    }
399
400
3.58k
    update_metadata_size();
401
3.58k
}
402
403
707k
int64_t RowsetMeta::get_metadata_size() const {
404
707k
    return sizeof(RowsetMeta) + _rowset_meta_pb.ByteSizeLong();
405
707k
}
406
407
744k
InvertedIndexFileInfo RowsetMeta::inverted_index_file_info(int seg_id) {
408
744k
    return _rowset_meta_pb.enable_inverted_index_file_info()
409
744k
                   ? (_rowset_meta_pb.inverted_index_file_info_size() > seg_id
410
23.6k
                              ? _rowset_meta_pb.inverted_index_file_info(seg_id)
411
18.4E
                              : InvertedIndexFileInfo())
412
744k
                   : InvertedIndexFileInfo();
413
744k
}
414
415
void RowsetMeta::add_inverted_index_files_info(
416
21.7k
        const std::vector<const InvertedIndexFileInfo*>& idx_file_info) {
417
21.7k
    _rowset_meta_pb.set_enable_inverted_index_file_info(true);
418
21.7k
    for (auto finfo : idx_file_info) {
419
6.09k
        auto* new_file_info = _rowset_meta_pb.add_inverted_index_file_info();
420
6.09k
        *new_file_info = *finfo;
421
6.09k
    }
422
21.7k
}
423
424
0
bool operator==(const RowsetMeta& a, const RowsetMeta& b) {
425
0
    if (a._rowset_id != b._rowset_id) return false;
426
0
    if (a._is_removed_from_rowset_meta != b._is_removed_from_rowset_meta) return false;
427
0
    if (!google::protobuf::util::MessageDifferencer::Equals(a._rowset_meta_pb, b._rowset_meta_pb))
428
0
        return false;
429
0
    return true;
430
0
}
431
432
} // namespace doris