Coverage Report

Created: 2026-07-15 03:26

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