Coverage Report

Created: 2026-07-31 19:12

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