Coverage Report

Created: 2026-09-21 17:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/segment.h
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
#pragma once
19
20
#include <butil/macros.h>
21
#include <gen_cpp/olap_file.pb.h>
22
#include <gen_cpp/segment_v2.pb.h>
23
#include <glog/logging.h>
24
25
#include <atomic>
26
#include <cstdint>
27
#include <functional>
28
#include <map>
29
#include <memory> // for unique_ptr
30
#include <optional>
31
#include <string>
32
#include <unordered_map>
33
34
#include "agent/be_exec_version_manager.h"
35
#include "common/be_mock_util.h"
36
#include "common/status.h" // Status
37
#include "core/column/column.h"
38
#include "core/data_type/data_type.h"
39
#include "io/cache/file_cache_common.h" // io::UInt128Wrapper returned by value
40
#include "io/fs/file_reader.h"
41
#include "io/fs/file_reader_writer_fwd.h"
42
#include "io/fs/file_system.h"
43
#include "io/io_common.h"
44
#include "runtime/descriptors.h"
45
#include "storage/cache/page_cache.h"
46
#include "storage/olap_common.h"
47
#include "storage/schema.h"
48
#include "storage/segment/page_handle.h"
49
#include "storage/tablet/tablet_schema.h"
50
#include "util/once.h"
51
#include "util/slice.h"
52
namespace doris {
53
class IDataType;
54
55
class ShortKeyIndexDecoder;
56
class ReadSchema;
57
class StorageReadOptions;
58
class PrimaryKeyIndexReader;
59
class RowwiseIterator;
60
struct RowLocation;
61
62
namespace segment_v2 {
63
64
class Segment;
65
class InvertedIndexIterator;
66
class IndexFileReader;
67
class IndexIterator;
68
class ColumnReader;
69
class ColumnIterator;
70
class ColumnReaderCache;
71
class ColumnMetaAccessor;
72
73
using SegmentSharedPtr = std::shared_ptr<Segment>;
74
75
struct SparseColumnCache;
76
using SparseColumnCacheSPtr = std::shared_ptr<SparseColumnCache>;
77
78
// key is column path, value is the sparse column cache
79
// now column path is only SPARSE_COLUMN_PATH, in the future, we can add more sparse column paths
80
using PathToSparseColumnCache = std::unordered_map<std::string, SparseColumnCacheSPtr>;
81
using PathToSparseColumnCacheUPtr = std::unique_ptr<PathToSparseColumnCache>;
82
83
struct BinaryColumnCache;
84
using BinaryColumnCacheSPtr = std::shared_ptr<BinaryColumnCache>;
85
using PathToBinaryColumnCache = std::unordered_map<std::string, BinaryColumnCacheSPtr>;
86
using PathToBinaryColumnCacheUPtr = std::unique_ptr<PathToBinaryColumnCache>;
87
88
// A Segment is used to represent a segment in memory format. When segment is
89
// generated, it won't be modified, so this struct aimed to help read operation.
90
// It will prepare all ColumnReader to create ColumnIterator as needed.
91
// And user can create a RowwiseIterator through new_iterator function.
92
//
93
// NOTE: This segment is used to a specified TabletSchema, when TabletSchema
94
// is changed, this segment can not be used any more. For example, after a schema
95
// change finished, client should disable all cached Segment for old TabletSchema.
96
class Segment : public std::enable_shared_from_this<Segment>, public MetadataAdder<Segment> {
97
public:
98
    static Status open(io::FileSystemSPtr fs, const std::string& path, int64_t tablet_id,
99
                       uint32_t segment_id, RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
100
                       const io::FileReaderOptions& reader_options,
101
                       std::shared_ptr<Segment>* output, InvertedIndexFileInfo idx_file_info = {},
102
                       OlapReaderStatistics* stats = nullptr,
103
                       const io::IOContext* io_ctx = nullptr);
104
105
    static io::UInt128Wrapper file_cache_key(std::string_view rowset_id, uint32_t seg_id);
106
0
    io::UInt128Wrapper file_cache_key() const {
107
0
        return file_cache_key(_rowset_id.to_string(), _segment_id);
108
0
    }
109
110
    ~Segment() override;
111
112
    int64_t get_metadata_size() const override;
113
    void update_metadata_size();
114
115
    Status new_iterator(ReadSchemaSPtr schema, const StorageReadOptions& read_options,
116
                        std::unique_ptr<RowwiseIterator>* iter);
117
118
    static Status new_default_iterator(const TabletColumn& tablet_column,
119
                                       std::unique_ptr<ColumnIterator>* iter);
120
121
9.99M
    uint32_t id() const { return _segment_id; }
122
123
1.05M
    RowsetId rowset_id() const { return _rowset_id; }
124
125
12.9M
    MOCK_FUNCTION uint32_t num_rows() const { return _num_rows; }
126
127
    // if variant_sparse_column_cache is nullptr, means the sparse column cache is not used
128
    Status new_column_iterator(const TabletColumn& tablet_column,
129
                               std::unique_ptr<ColumnIterator>* iter, const StorageReadOptions* opt,
130
                               const std::unordered_map<int32_t, PathToBinaryColumnCacheUPtr>*
131
                                       variant_sparse_column_cache = nullptr);
132
133
    Status new_index_iterator(const TabletColumn& tablet_column, const TabletIndex* index_meta,
134
                              const StorageReadOptions& read_options,
135
                              std::unique_ptr<IndexIterator>* iter);
136
137
804k
    const ShortKeyIndexDecoder* get_short_key_index() const {
138
804k
        DCHECK(_load_index_once.has_called() && _load_index_once.stored_result().ok());
139
804k
        return _sk_index_decoder.get();
140
804k
    }
141
142
3.81M
    const PrimaryKeyIndexReader* get_primary_key_index() const {
143
3.81M
        DCHECK(_load_index_once.has_called() && _load_index_once.stored_result().ok());
144
3.81M
        return _pk_index_reader.get();
145
3.81M
    }
146
147
    Status lookup_row_key(const Slice& key, const TabletSchema* latest_schema, bool with_seq_col,
148
                          bool with_rowid, RowLocation* row_location, OlapReaderStatistics* stats,
149
                          std::string* encoded_seq_value = nullptr,
150
                          const io::IOContext* io_ctx = nullptr);
151
152
    Status read_key_by_rowid(uint32_t row_id, std::string* key);
153
154
    // row_ids must be strictly increasing.
155
    // `read_column` is what `slot` resolves to, or its variant parent column for a subpath slot.
156
    Status seek_and_read_by_rowid(const TabletColumn& read_column, SlotDescriptor* slot,
157
                                  const std::vector<uint32_t>& row_ids, MutableColumnPtr& result,
158
                                  StorageReadOptions& storage_read_options,
159
                                  std::unique_ptr<ColumnIterator>& iterator_hint);
160
161
    Status load_index(OlapReaderStatistics* stats, const io::IOContext* io_ctx = nullptr);
162
163
    Status load_pk_index_and_bf(OlapReaderStatistics* stats, const io::IOContext* io_ctx = nullptr);
164
165
25
    void update_healthy_status(Status new_status) { _healthy_status.update(new_status); }
166
    // The segment is loaded into SegmentCache and then will load indices, if there are something wrong
167
    // during loading indices, should remove it from SegmentCache. If not, it will always report error during
168
    // query. So we add a healthy status API, the caller should check the healhty status before using the segment.
169
    Status healthy_status();
170
171
1.89M
    std::string min_key() {
172
1.89M
        DCHECK(_tablet_schema->keys_type() == UNIQUE_KEYS && _pk_index_meta != nullptr);
173
1.89M
        return _pk_index_meta->min_key();
174
1.89M
    }
175
1.70M
    std::string max_key() {
176
1.70M
        DCHECK(_tablet_schema->keys_type() == UNIQUE_KEYS && _pk_index_meta != nullptr);
177
1.70M
        return _pk_index_meta->max_key();
178
1.70M
    }
179
180
22.7k
    io::FileReaderSPtr file_reader() { return _file_reader; }
181
182
    // Including the column reader memory.
183
    // another method `get_metadata_size` not include the column reader, only the segment object itself.
184
281k
    int64_t meta_mem_usage() const { return _meta_mem_usage; }
185
186
    // PK pages are tracked by PKIndexPageCache, but their pinned bytes must also
187
    // count toward SegmentCache eviction. Do not add these bytes to metadata tracking.
188
86.4k
    size_t cache_charge() const {
189
86.4k
        return _meta_mem_usage + _pk_index_cache_bytes.load(std::memory_order_relaxed);
190
86.4k
    }
191
192
    // Install before publishing this segment in SegmentCache; immutable afterwards.
193
63.6k
    void set_cache_charge_callback(std::function<void(size_t)> callback) {
194
63.6k
        DCHECK(!_cache_charge_callback);
195
63.6k
        _cache_charge_callback = std::move(callback);
196
63.6k
    }
197
198
    // Variant paths use segment metadata; other columns use `read_type`.
199
    std::shared_ptr<const IDataType> get_data_type_of(const TabletColumn& read_column,
200
                                                      const DataTypePtr& read_type,
201
                                                      const StorageReadOptions& read_options);
202
203
    // If column in segment is the same type in schema, then it is safe to apply predicate.
204
    // `ordinal` is a read-schema ordinal (the coordinate ColumnPredicate::column_id() carries).
205
    bool can_apply_predicate_safely(
206
            int ordinal, const ReadSchema& schema,
207
            const std::map<std::string, DataTypePtr>& target_cast_type_for_variants,
208
2.47M
            const StorageReadOptions& read_options) {
209
2.47M
        const TabletColumn* col = schema.column(ordinal);
210
18.4E
        DCHECK(col != nullptr) << "Column not found in schema for ordinal=" << ordinal;
211
2.47M
        DataTypePtr storage_column_type =
212
2.47M
                get_data_type_of(*col, schema.data_type(ordinal), read_options);
213
2.48M
        if (storage_column_type == nullptr || col->type() != FieldType::OLAP_FIELD_TYPE_VARIANT ||
214
2.47M
            !target_cast_type_for_variants.contains(col->name())) {
215
            // Default column iterator or not variant column
216
2.47M
            return true;
217
2.47M
        }
218
18.4E
        if (storage_column_type->equals(*target_cast_type_for_variants.at(col->name()))) {
219
958
            return true;
220
18.4E
        } else {
221
18.4E
            return false;
222
18.4E
        }
223
18.4E
    }
224
225
    // The tso column (__DORIS_BINLOG_TSO__) is a NULL placeholder on disk on a
226
    // single-version binlog segment, replaced with the real commit_tso at read time
227
    // (SegmentIterator::_update_tso_col_if_needed). Its zonemap reflects the placeholder, so
228
    // it must NOT drive zonemap pruning. Mirrors the guards of _update_tso_col_if_needed.
229
    // Returns false for range (compaction) segments whose on-disk value is real.
230
    bool is_tso_placeholder_col(int cid, const ReadSchema& schema,
231
                                const StorageReadOptions& read_options) const;
232
233
21
    const TabletSchemaSPtr& tablet_schema() const { return _tablet_schema; }
234
235
    // get the column reader by tablet column, return NOT_FOUND if not found reader in this segment
236
    Status get_column_reader(const TabletColumn& col, std::shared_ptr<ColumnReader>* column_reader,
237
                             OlapReaderStatistics* stats, const io::IOContext* io_ctx = nullptr,
238
                             std::optional<Field> const_value = std::nullopt);
239
240
    // get the column reader by column unique id, return NOT_FOUND if not found reader in this segment
241
    Status get_column_reader(int32_t col_uid, std::shared_ptr<ColumnReader>* column_reader,
242
                             OlapReaderStatistics* stats, const io::IOContext* io_ctx = nullptr,
243
                             std::optional<Field> const_value = std::nullopt);
244
245
    Status traverse_column_meta_pbs(const std::function<void(const ColumnMetaPB&)>& visitor);
246
247
    // Returns the cached raw_data_bytes for the given column unique id, or 0 if not found.
248
    // Data is populated during _create_column_meta (under call_once), so thread-safe after init.
249
16.1M
    uint64_t column_raw_data_bytes(int32_t column_uid) const {
250
16.1M
        auto it = _column_uid_to_raw_bytes.find(column_uid);
251
18.4E
        return it != _column_uid_to_raw_bytes.end() ? it->second : 0;
252
16.1M
    }
253
254
    static StoragePageCache::CacheKey get_segment_footer_cache_key(
255
            const io::FileReaderSPtr& file_reader);
256
257
private:
258
    DISALLOW_COPY_AND_ASSIGN(Segment);
259
    Segment(uint32_t segment_id, RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
260
            InvertedIndexFileInfo idx_file_info = InvertedIndexFileInfo());
261
    static Status _open(io::FileSystemSPtr fs, const std::string& path, uint32_t segment_id,
262
                        RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
263
                        const io::FileReaderOptions& reader_options,
264
                        std::shared_ptr<Segment>* output, InvertedIndexFileInfo idx_file_info,
265
                        OlapReaderStatistics* stats = nullptr,
266
                        const io::IOContext* io_ctx = nullptr);
267
    // open segment file and read the minimum amount of necessary information (footer)
268
    Status _open(OlapReaderStatistics* stats, const io::IOContext* io_ctx = nullptr);
269
    Status _parse_footer(std::shared_ptr<SegmentFooterPB>& footer,
270
                         OlapReaderStatistics* stats = nullptr,
271
                         const io::IOContext* io_ctx = nullptr);
272
    Status _create_column_meta(const SegmentFooterPB& footer, OlapReaderStatistics* stats = nullptr,
273
                               const io::IOContext* io_ctx = nullptr);
274
    Status _load_pk_bloom_filter(OlapReaderStatistics* stats,
275
                                 const io::IOContext* io_ctx = nullptr);
276
277
    Status _write_error_file(size_t file_size, size_t offset, size_t bytes_read, char* data,
278
                             io::IOContext& io_ctx);
279
280
    Status _open_index_file_reader();
281
282
    Status _create_column_meta_once(OlapReaderStatistics* stats,
283
                                    const io::IOContext* io_ctx = nullptr);
284
285
    virtual Status _get_segment_footer(std::shared_ptr<SegmentFooterPB>&,
286
                                       OlapReaderStatistics* stats,
287
                                       const io::IOContext* io_ctx = nullptr);
288
289
    StoragePageCache::CacheKey get_segment_footer_cache_key() const;
290
291
    friend class SegmentIterator;
292
    friend class ColumnReaderCache;
293
    friend class MockSegment;
294
295
    io::FileSystemSPtr _fs;
296
    io::FileReaderSPtr _file_reader;
297
    // Relative path passed to `open`, used to derive the inverted index path (see
298
    // _open_index_file_reader).
299
    std::string _seg_path;
300
    uint32_t _segment_id;
301
    uint32_t _num_rows;
302
    AtomicStatus _healthy_status;
303
304
    // 1. Tracking memory use by segment meta data such as footer or index page.
305
    // 2. Tracking memory use by segment column reader
306
    // The memory consumed by querying is tracked in segment iterator.
307
    int64_t _meta_mem_usage;
308
    int64_t _tracked_meta_mem_usage = 0;
309
    std::atomic<size_t> _pk_index_cache_bytes {0};
310
    std::function<void(size_t)> _cache_charge_callback;
311
312
    RowsetId _rowset_id;
313
    TabletSchemaSPtr _tablet_schema;
314
315
    std::unique_ptr<PrimaryKeyIndexMetaPB> _pk_index_meta;
316
    PagePointerPB _sk_index_page;
317
318
    // Limited cache for column readers
319
    std::unique_ptr<ColumnReaderCache> _column_reader_cache;
320
321
    // Centralized accessor for column metadata layout and uid->column_ordinal mapping.
322
    std::unique_ptr<ColumnMetaAccessor> _column_meta_accessor;
323
324
    // Init from ColumnMetaPB in SegmentFooterPB
325
    // map column unique id ---> it's inner data type
326
    std::map<int32_t, std::shared_ptr<const IDataType>> _file_column_types;
327
328
    // used to guarantee that short key index will be loaded at most once in a thread-safe way
329
    DorisCallOnce<Status> _load_index_once;
330
    // used to guarantee that primary key bloom filter will be loaded at most once in a thread-safe way
331
    DorisCallOnce<Status> _load_pk_bf_once;
332
333
    DorisCallOnce<Status> _create_column_meta_once_call;
334
335
    std::weak_ptr<SegmentFooterPB> _footer_pb;
336
337
    // Cached raw_data_bytes per column unique id, populated once in _create_column_meta().
338
    std::unordered_map<int32_t, uint64_t> _column_uid_to_raw_bytes;
339
340
    // used to hold short key index page in memory
341
    PageHandle _sk_index_handle;
342
    // short key index decoder
343
    // all content is in memory
344
    std::unique_ptr<ShortKeyIndexDecoder> _sk_index_decoder;
345
    // primary key index reader
346
    std::unique_ptr<PrimaryKeyIndexReader> _pk_index_reader;
347
    std::mutex _open_lock;
348
    // inverted index file reader
349
    std::shared_ptr<IndexFileReader> _index_file_reader;
350
    DorisCallOnce<Status> _index_file_reader_open;
351
352
    InvertedIndexFileInfo _idx_file_info;
353
    int64_t _tablet_id = -1;
354
355
    int _be_exec_version = BeExecVersionManager::get_newest_version();
356
};
357
358
} // namespace segment_v2
359
} // namespace doris