Coverage Report

Created: 2026-06-06 15:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/tablet/tablet_reader.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 <gen_cpp/Descriptors_types.h>
21
#include <gen_cpp/PaloInternalService_types.h>
22
#include <gen_cpp/PlanNodes_types.h>
23
#include <stddef.h>
24
#include <stdint.h>
25
26
#include <memory>
27
#include <set>
28
#include <string>
29
#include <unordered_set>
30
#include <utility>
31
#include <vector>
32
33
#include "agent/be_exec_version_manager.h"
34
#include "common/status.h"
35
#include "exprs/function_filter.h"
36
#include "io/io_common.h"
37
#include "storage/delete/delete_handler.h"
38
#include "storage/iterators.h"
39
#include "storage/olap_common.h"
40
#include "storage/olap_tuple.h"
41
#include "storage/predicate/filter_olap_param.h"
42
#include "storage/row_cursor.h"
43
#include "storage/rowid_conversion.h"
44
#include "storage/rowset/rowset.h"
45
#include "storage/rowset/rowset_meta.h"
46
#include "storage/rowset/rowset_reader.h"
47
#include "storage/rowset/rowset_reader_context.h"
48
#include "storage/tablet/base_tablet.h"
49
#include "storage/tablet/tablet_fwd.h"
50
51
namespace doris {
52
53
class RuntimeState;
54
class BitmapFilterFuncBase;
55
class BloomFilterFuncBase;
56
class ColumnPredicate;
57
class DeleteBitmap;
58
class HybridSetBase;
59
class RuntimeProfile;
60
class ScanFilterProfile;
61
62
class VCollectIterator;
63
class Block;
64
class VExpr;
65
class Arena;
66
class VExprContext;
67
68
// Used to compare row with input scan key. Scan key only contains key columns,
69
// row contains all key columns, which is superset of key columns.
70
// So we should compare the common prefix columns of lhs and rhs.
71
//
72
// NOTE: if you are not sure if you can use it, please don't use this function.
73
0
inline int compare_row_key(const RowCursor& lhs, const RowCursor& rhs) {
74
0
    auto cmp_cids = std::min(lhs.field_count(), rhs.field_count());
75
0
    for (uint32_t cid = 0; cid < cmp_cids; ++cid) {
76
0
        const auto& lf = lhs.field(cid);
77
0
        const auto& rf = rhs.field(cid);
78
        // Handle nulls: null < non-null
79
0
        if (lf.is_null() != rf.is_null()) {
80
0
            return lf.is_null() ? -1 : 1;
81
0
        }
82
0
        if (lf.is_null()) {
83
0
            continue; // both null
84
0
        }
85
0
        auto cmp = lf <=> rf;
86
0
        if (cmp < 0) return -1;
87
0
        if (cmp > 0) return 1;
88
0
    }
89
0
    return 0;
90
0
}
91
92
class TabletReader {
93
    struct KeysParam {
94
        std::vector<RowCursor> start_keys;
95
        std::vector<RowCursor> end_keys;
96
        bool start_key_include = false;
97
        bool end_key_include = false;
98
    };
99
100
public:
101
    // Params for Reader,
102
    // mainly include tablet, data version and fetch range.
103
    struct ReaderParams {
104
0
        bool has_single_version() const {
105
0
            return (rs_splits.size() == 1 &&
106
0
                    rs_splits[0].rs_reader->rowset()->start_version() == 0 &&
107
0
                    !rs_splits[0].rs_reader->rowset()->rowset_meta()->is_segments_overlapping()) ||
108
0
                   (rs_splits.size() == 2 &&
109
0
                    rs_splits[0].rs_reader->rowset()->rowset_meta()->num_rows() == 0 &&
110
0
                    rs_splits[1].rs_reader->rowset()->start_version() == 2 &&
111
0
                    !rs_splits[1].rs_reader->rowset()->rowset_meta()->is_segments_overlapping());
112
0
        }
113
114
3
        int get_be_exec_version() const {
115
3
            if (runtime_state) {
116
0
                return runtime_state->be_exec_version();
117
0
            }
118
3
            return BeExecVersionManager::get_newest_version();
119
3
        }
120
121
358
        void set_read_source(TabletReadSource read_source, bool skip_delete_bitmap = false) {
122
358
            rs_splits = std::move(read_source.rs_splits);
123
358
            delete_predicates = std::move(read_source.delete_predicates);
124
#ifndef BE_TEST
125
            if (tablet->enable_unique_key_merge_on_write() && !skip_delete_bitmap) {
126
                delete_bitmap = std::move(read_source.delete_bitmap);
127
            }
128
#endif
129
358
        }
130
131
        BaseTabletSPtr tablet;
132
        TabletSchemaSPtr tablet_schema;
133
        ReaderType reader_type = ReaderType::READER_QUERY;
134
        bool direct_mode = false;
135
        bool aggregation = false;
136
        // for compaction, schema_change, check_sum: we don't use page cache
137
        // for query, when the BE config disable_storage_page_cache is false, we use page cache
138
        bool use_page_cache = false;
139
        Version version = Version(-1, 0);
140
141
        std::vector<OlapTuple> start_key;
142
        std::vector<OlapTuple> end_key;
143
        bool start_key_include = false;
144
        bool end_key_include = false;
145
146
        std::vector<std::shared_ptr<ColumnPredicate>> predicates;
147
        std::vector<FunctionFilter> function_filters;
148
        std::vector<RowsetMetaSharedPtr> delete_predicates;
149
        // slots that cast may be eliminated in storage layer
150
        std::map<std::string, DataTypePtr> target_cast_type_for_variants;
151
152
        std::map<int32_t, TColumnAccessPaths> all_access_paths;
153
        std::map<int32_t, TColumnAccessPaths> predicate_access_paths;
154
155
        std::vector<RowSetSplits> rs_splits;
156
        // For unique key table with merge-on-write
157
        DeleteBitmapPtr delete_bitmap = nullptr;
158
159
        // return_columns is init from query schema
160
        std::vector<ColumnId> return_columns;
161
        // output_columns only contain columns in OrderByExprs and outputExprs
162
        std::set<int32_t> output_columns;
163
        RuntimeProfile* profile = nullptr;
164
        RuntimeState* runtime_state = nullptr;
165
        std::shared_ptr<ScanFilterProfile> scan_filter_profile;
166
        ScanFilterHandle key_range_scan_filter;
167
168
        // use only in vec exec engine
169
        std::vector<ColumnId>* origin_return_columns = nullptr;
170
        std::unordered_set<uint32_t>* tablet_columns_convert_to_null_set = nullptr;
171
        TPushAggOp::type push_down_agg_type_opt = TPushAggOp::NONE;
172
        VExprContextSPtrs common_expr_ctxs_push_down;
173
174
        // used for compaction to record row ids
175
        bool record_rowids = false;
176
        RowIdConversion* rowid_conversion = nullptr;
177
        std::vector<int> topn_filter_source_node_ids;
178
        int topn_filter_target_node_id = -1;
179
        // used for special optimization for query : ORDER BY key LIMIT n
180
        bool read_orderby_key = false;
181
        // used for special optimization for query : ORDER BY key DESC LIMIT n
182
        bool read_orderby_key_reverse = false;
183
        // For rows with the same key, use ascending order (small-to-large) for tie-breakers.
184
        // For example, use lower rowset version / segment id first.
185
        bool use_insert_order_when_same = false;
186
        // num of columns for orderby key
187
        size_t read_orderby_key_num_prefix_columns = 0;
188
        // limit of rows for read_orderby_key
189
        size_t read_orderby_key_limit = 0;
190
        // for vertical compaction
191
        bool is_key_column_group = false;
192
        std::vector<uint32_t> key_group_cluster_key_idxes;
193
194
        // For sparse column compaction optimization
195
        // When true, use optimized path for sparse wide tables
196
        bool enable_sparse_optimization = false;
197
198
        bool is_segcompaction = false;
199
200
        // Enable value predicate pushdown for MOR tables
201
        bool enable_mor_value_predicate_pushdown = false;
202
203
        std::vector<RowwiseIteratorUPtr>* segment_iters_ptr = nullptr;
204
205
        void check_validation() const;
206
207
        int64_t batch_size = -1;
208
209
        std::map<ColumnId, VExprContextSPtr> virtual_column_exprs;
210
        std::map<ColumnId, size_t> vir_cid_to_idx_in_block;
211
        std::map<size_t, DataTypePtr> vir_col_idx_to_type;
212
213
        std::shared_ptr<ScoreRuntime> score_runtime;
214
        CollectionStatisticsPtr collection_statistics;
215
        std::shared_ptr<segment_v2::AnnTopNRuntime> ann_topn_runtime;
216
217
        uint64_t condition_cache_digest = 0;
218
219
        // General LIMIT budget forwarded to SegmentIterator. -1 means no limit.
220
        int64_t general_read_limit = -1;
221
    };
222
223
399
    TabletReader() = default;
224
225
399
    virtual ~TabletReader() = default;
226
227
    TabletReader(const TabletReader&) = delete;
228
    void operator=(const TabletReader&) = delete;
229
230
    // Initialize TabletReader with tablet, data version and fetch range.
231
    virtual Status init(const ReaderParams& read_params);
232
233
    // Read next block with aggregation.
234
    // Return OK and set `*eof` to false when next block is read
235
    // Return OK and set `*eof` to true when no more rows can be read.
236
    // Return others when unexpected error happens.
237
0
    virtual Status next_block_with_aggregation(Block* block, bool* eof) {
238
0
        return Status::Error<ErrorCode::READER_INITIALIZE_ERROR>(
239
0
                "TabletReader not support next_block_with_aggregation");
240
0
    }
241
242
48
    virtual uint64_t merged_rows() const { return _merged_rows; }
243
244
145
    uint64_t filtered_rows() const {
245
145
        return _stats.rows_del_filtered + _stats.rows_del_by_bitmap +
246
145
               _stats.rows_conditions_filtered + _stats.rows_vec_del_cond_filtered +
247
145
               _stats.rows_vec_cond_filtered + _stats.rows_short_circuit_cond_filtered;
248
145
    }
249
250
0
    void set_batch_size(int batch_size) { _reader_context.batch_size = batch_size; }
251
252
0
    int batch_size() const { return _reader_context.batch_size; }
253
254
280k
    size_t batch_max_rows() const { return _reader_context.batch_size; }
255
256
0
    void set_preferred_block_size_bytes(size_t bytes) {
257
0
        _reader_context.preferred_block_size_bytes = bytes;
258
0
    }
259
260
    // Returns the preferred output block byte budget. Subclasses that support adaptive batch size
261
    // should override this; the base returns 0 (disabled) so VCollectIterator degrades safely
262
    // when called through a TabletReader* that has not been configured.
263
0
    virtual size_t preferred_block_size_bytes() const { return 0; }
264
265
1.09k
    const OlapReaderStatistics& stats() const { return _stats; }
266
0
    OlapReaderStatistics* mutable_stats() { return &_stats; }
267
268
0
    virtual void update_profile(RuntimeProfile* profile) {}
269
    static Status init_reader_params_and_create_block(
270
            TabletSharedPtr tablet, ReaderType reader_type,
271
            const std::vector<RowsetSharedPtr>& input_rowsets,
272
            TabletReader::ReaderParams* reader_params, Block* block);
273
274
protected:
275
    friend class VCollectIterator;
276
    friend class DeleteHandler;
277
278
    Status _init_params(const ReaderParams& read_params);
279
280
    Status _capture_rs_readers(const ReaderParams& read_params);
281
282
    Status _init_keys_param(const ReaderParams& read_params);
283
284
    Status _init_orderby_keys_param(const ReaderParams& read_params);
285
286
    Status _init_conditions_param(const ReaderParams& read_params);
287
288
    virtual std::shared_ptr<ColumnPredicate> _parse_to_predicate(
289
            const FunctionFilter& function_filter);
290
291
    Status _init_delete_condition(const ReaderParams& read_params);
292
293
    Status _init_return_columns(const ReaderParams& read_params);
294
295
686
    const BaseTabletSPtr& tablet() { return _tablet; }
296
    // If original column is a variant type column, and it's predicate is normalized
297
    // so in order to get the real type of column predicate, we need to reset type
298
    // according to the related type in `target_cast_type_for_variants`.Since variant is not
299
    // an predicate applicable type.Otherwise return the original tablet column.
300
    // Eg. `where cast(v:a as bigint) > 1` will elimate cast, and materialize this variant column
301
    // to type bigint
302
    TabletColumn materialize_column(const TabletColumn& orig);
303
304
240
    const TabletSchema& tablet_schema() { return *_tablet_schema; }
305
306
    Arena _predicate_arena;
307
    std::vector<ColumnId> _return_columns;
308
309
    // used for special optimization for query : ORDER BY key [ASC|DESC] LIMIT n
310
    // columns for orderby keys
311
    std::vector<uint32_t> _orderby_key_columns;
312
    // only use in outer join which change the column nullable which must keep same in
313
    // vec query engine
314
    std::unordered_set<uint32_t>* _tablet_columns_convert_to_null_set = nullptr;
315
316
    BaseTabletSPtr _tablet;
317
    RowsetReaderContext _reader_context;
318
    TabletSchemaSPtr _tablet_schema;
319
    KeysParam _keys_param;
320
    std::vector<bool> _is_lower_keys_included;
321
    std::vector<bool> _is_upper_keys_included;
322
    std::vector<std::shared_ptr<ColumnPredicate>> _col_predicates;
323
    std::vector<std::shared_ptr<ColumnPredicate>> _value_col_predicates;
324
    DeleteHandler _delete_handler;
325
326
    // Indicates whether the tablets has do a aggregation in storage engine.
327
    bool _aggregation = false;
328
    // for agg query, we don't need to finalize when scan agg object data
329
    ReaderType _reader_type = ReaderType::READER_QUERY;
330
    bool _next_delete_flag = false;
331
    bool _delete_sign_available = false;
332
    bool _filter_delete = false;
333
    int32_t _sequence_col_idx = -1;
334
    bool _direct_mode = false;
335
336
    std::vector<uint32_t> _key_cids;
337
    std::vector<uint32_t> _value_cids;
338
339
    uint64_t _merged_rows = 0;
340
    OlapReaderStatistics _stats;
341
};
342
343
} // namespace doris