Coverage Report

Created: 2026-08-21 18:55

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 "io/io_common.h"
36
#include "storage/delete/delete_handler.h"
37
#include "storage/iterators.h"
38
#include "storage/olap_common.h"
39
#include "storage/olap_tuple.h"
40
#include "storage/predicate/filter_olap_param.h"
41
#include "storage/row_cursor.h"
42
#include "storage/rowid_conversion.h"
43
#include "storage/rowset/rowset.h"
44
#include "storage/rowset/rowset_meta.h"
45
#include "storage/rowset/rowset_reader.h"
46
#include "storage/rowset/rowset_reader_context.h"
47
#include "storage/tablet/base_tablet.h"
48
#include "storage/tablet/tablet_fwd.h"
49
50
namespace doris {
51
52
class RuntimeState;
53
class BloomFilterFuncBase;
54
class ColumnPredicate;
55
class DeleteBitmap;
56
class HybridSetBase;
57
class RuntimeProfile;
58
59
class VCollectIterator;
60
class Block;
61
class VExpr;
62
class VExprContext;
63
64
// Used to compare row with input scan key. Scan key only contains key columns,
65
// row contains all key columns, which is superset of key columns.
66
// So we should compare the common prefix columns of lhs and rhs.
67
//
68
// NOTE: if you are not sure if you can use it, please don't use this function.
69
0
inline int compare_row_key(const RowCursor& lhs, const RowCursor& rhs) {
70
0
    auto cmp_cids = std::min(lhs.field_count(), rhs.field_count());
71
0
    for (uint32_t cid = 0; cid < cmp_cids; ++cid) {
72
0
        const auto& lf = lhs.field(cid);
73
0
        const auto& rf = rhs.field(cid);
74
        // Handle nulls: null < non-null
75
0
        if (lf.is_null() != rf.is_null()) {
76
0
            return lf.is_null() ? -1 : 1;
77
0
        }
78
0
        if (lf.is_null()) {
79
0
            continue; // both null
80
0
        }
81
0
        auto cmp = lf <=> rf;
82
0
        if (cmp < 0) return -1;
83
0
        if (cmp > 0) return 1;
84
0
    }
85
0
    return 0;
86
0
}
87
88
class TabletReader {
89
    struct KeysParam {
90
        std::vector<RowCursor> start_keys;
91
        std::vector<RowCursor> end_keys;
92
        bool start_key_include = false;
93
        bool end_key_include = false;
94
    };
95
96
public:
97
    // Params for Reader,
98
    // mainly include tablet, data version and fetch range.
99
    struct ReaderParams {
100
0
        bool has_single_version() const {
101
0
            return (rs_splits.size() == 1 &&
102
0
                    rs_splits[0].rs_reader->rowset()->start_version() == 0 &&
103
0
                    !rs_splits[0].rs_reader->rowset()->rowset_meta()->is_segments_overlapping()) ||
104
0
                   (rs_splits.size() == 2 &&
105
0
                    rs_splits[0].rs_reader->rowset()->rowset_meta()->num_rows() == 0 &&
106
0
                    rs_splits[1].rs_reader->rowset()->start_version() == 2 &&
107
0
                    !rs_splits[1].rs_reader->rowset()->rowset_meta()->is_segments_overlapping());
108
0
        }
109
110
3
        int get_be_exec_version() const {
111
3
            if (runtime_state) {
112
0
                return runtime_state->be_exec_version();
113
0
            }
114
3
            return BeExecVersionManager::get_newest_version();
115
3
        }
116
117
427
        void set_read_source(TabletReadSource read_source, bool skip_delete_bitmap = false) {
118
427
            rs_splits = std::move(read_source.rs_splits);
119
427
            delete_predicates = std::move(read_source.delete_predicates);
120
#ifndef BE_TEST
121
            if (!skip_delete_bitmap && tablet->need_read_delete_bitmap()) {
122
                delete_bitmap = std::move(read_source.delete_bitmap);
123
            }
124
#endif
125
427
        }
126
127
        BaseTabletSPtr tablet;
128
        TabletSchemaSPtr tablet_schema;
129
        ReaderType reader_type = ReaderType::READER_QUERY;
130
        bool read_row_binlog = false;
131
        bool direct_mode = false;
132
        bool aggregation = false;
133
        // for compaction, schema_change, check_sum: we don't use page cache
134
        // for query, when the BE config disable_storage_page_cache is false, we use page cache
135
        bool use_page_cache = false;
136
        Version version = Version(-1, 0);
137
138
        std::vector<OlapTuple> start_key;
139
        std::vector<OlapTuple> end_key;
140
        bool start_key_include = false;
141
        bool end_key_include = false;
142
143
        std::vector<std::shared_ptr<ColumnPredicate>> predicates;
144
        std::vector<RowsetMetaSharedPtr> delete_predicates;
145
        // slots that cast may be eliminated in storage layer
146
        std::map<std::string, DataTypePtr> target_cast_type_for_variants;
147
148
        std::map<int32_t, TColumnAccessPaths> all_access_paths;
149
        std::map<int32_t, TColumnAccessPaths> predicate_access_paths;
150
151
        std::vector<RowSetSplits> rs_splits;
152
        // For unique key table with merge-on-write
153
        DeleteBitmapPtr delete_bitmap = nullptr;
154
155
        // The read schema of every Block at the TabletReader boundary.
156
        // Query scanners construct the FE-slot prefix in scan-tuple order;
157
        // TabletReader may append storage-only delete-predicate columns.
158
        ReadSchemaSPtr read_schema;
159
        // output_columns only contain columns in OrderByExprs and outputExprs
160
        // (column unique ids, not ordinals)
161
        std::set<int32_t> output_columns;
162
        // Ordinals (positions in read_schema) of extra storage key columns
163
        // that are present only for scan-schema alignment.
164
        // Example: for AGG keys (k1, k2), a query that returns k2 can scan
165
        // (k1, k2) and project away k1. Direct readers may avoid reading such
166
        // columns only if the lower iterator proves their real values are not
167
        // required by predicates, delete conditions, or expressions.
168
        std::set<ColumnId> extra_columns;
169
        RuntimeProfile* profile = nullptr;
170
        RuntimeState* runtime_state = nullptr;
171
172
        TPushAggOp::type push_down_agg_type_opt = TPushAggOp::NONE;
173
        VExprContextSPtrs common_expr_ctxs_push_down;
174
175
        // used for compaction to record row ids
176
        bool record_rowids = false;
177
        RowIdConversion* rowid_conversion = nullptr;
178
        std::vector<int> topn_filter_source_node_ids;
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
        // Force a key-ordered merge across all segments even when their key ranges do not
187
        // overlap. By default a rowset reader can skip the merge heap if its segments are
188
        // mono-ascending and disjoint, but row-binlog scans require strict global key order
189
        // (e.g. so MIN_DELTA can group consecutive same-key changes), so this flag is set.
190
        // See BetaRowsetReader::is_merge_iterator() in beta_rowset_reader.h:62.
191
        bool force_key_ordered_read = false;
192
        // num of columns for orderby key
193
        size_t read_orderby_key_num_prefix_columns = 0;
194
        // limit of rows for read_orderby_key
195
        size_t read_orderby_key_limit = 0;
196
        // for vertical compaction
197
        bool is_key_column_group = false;
198
        std::vector<uint32_t> key_group_cluster_key_idxes;
199
200
        // For sparse column compaction optimization
201
        // When true, use optimized path for sparse wide tables
202
        bool enable_sparse_optimization = false;
203
204
        bool is_segcompaction = false;
205
206
        // Enable value predicate pushdown for MOR tables
207
        bool enable_mor_value_predicate_pushdown = false;
208
209
        std::vector<RowwiseIteratorUPtr>* segment_iters_ptr = nullptr;
210
211
        void check_validation() const;
212
213
        int64_t batch_size = -1;
214
215
        // virtual column ordinal (position in read_schema) -> expression
216
        std::map<ColumnId, VExprContextSPtr> virtual_column_exprs;
217
218
        std::shared_ptr<ScoreRuntime> score_runtime;
219
        CollectionStatisticsPtr collection_statistics;
220
        std::shared_ptr<segment_v2::AnnTopNRuntime> ann_topn_runtime;
221
222
        uint64_t condition_cache_digest = 0;
223
224
        // General LIMIT budget forwarded to SegmentIterator. -1 means no limit.
225
        int64_t general_read_limit = -1;
226
        TBinlogScanType::type binlog_scan_type = TBinlogScanType::NONE;
227
    };
228
229
482
    TabletReader() = default;
230
231
482
    virtual ~TabletReader() = default;
232
233
    TabletReader(const TabletReader&) = delete;
234
    void operator=(const TabletReader&) = delete;
235
236
    // Initialize TabletReader with tablet, data version and fetch range.
237
    virtual Status init(const ReaderParams& read_params);
238
239
    // Read next block with aggregation.
240
    // Return OK and set `*eof` to false when next block is read
241
    // Return OK and set `*eof` to true when no more rows can be read.
242
    // Return others when unexpected error happens.
243
0
    virtual Status next_block_with_aggregation(Block* block, bool* eof) {
244
0
        return Status::Error<ErrorCode::READER_INITIALIZE_ERROR>(
245
0
                "TabletReader not support next_block_with_aggregation");
246
0
    }
247
248
48
    virtual uint64_t merged_rows() const { return _merged_rows; }
249
250
181
    uint64_t filtered_rows() const {
251
181
        return _stats.rows_del_filtered + _stats.rows_del_by_bitmap +
252
181
               _stats.rows_conditions_filtered + _stats.rows_vec_del_cond_filtered +
253
181
               _stats.rows_vec_cond_filtered + _stats.rows_short_circuit_cond_filtered;
254
181
    }
255
256
0
    void set_batch_size(int batch_size) { _reader_context.batch_size = batch_size; }
257
258
280k
    size_t batch_max_rows() const { return _reader_context.batch_size; }
259
260
0
    void set_preferred_block_size_bytes(size_t bytes) {
261
0
        _reader_context.preferred_block_size_bytes = bytes;
262
0
    }
263
264
    // Returns the preferred output block byte budget. Subclasses that support adaptive batch size
265
    // should override this; the base returns 0 (disabled) so VCollectIterator degrades safely
266
    // when called through a TabletReader* that has not been configured.
267
0
    virtual size_t preferred_block_size_bytes() const { return 0; }
268
269
1.30k
    const OlapReaderStatistics& stats() const { return _stats; }
270
2
    OlapReaderStatistics* mutable_stats() { return &_stats; }
271
272
2
    virtual void update_profile(RuntimeProfile* profile) {}
273
274
    // Remove the delete-condition columns from `all_access_paths` so they fall back to a full
275
    // read (a meta-only read would make the storage delete predicate match nothing and leak
276
    // deleted rows).
277
    static void remove_delete_columns_from_access_paths(
278
            const DeleteHandler& delete_handler, const ReadSchema& read_schema,
279
            std::map<int32_t, TColumnAccessPaths>& all_access_paths);
280
281
protected:
282
    friend class VCollectIterator;
283
284
    Status _init_params(const ReaderParams& read_params);
285
286
    Status _capture_rs_readers(const ReaderParams& read_params);
287
288
    Status _init_keys_param(const ReaderParams& read_params);
289
290
    Status _init_orderby_keys_param(const ReaderParams& read_params);
291
292
    Status _init_column_predicates(const ReaderParams& read_params);
293
294
    Status _init_delete_condition(const ReaderParams& read_params);
295
296
820
    const BaseTabletSPtr& tablet() { return _tablet; }
297
298
    // The read schema shared by the caller, TabletReader, VCollect and each rowset reader.
299
    ReadSchemaSPtr _read_schema;
300
301
    // used for special optimization for query : ORDER BY key [ASC|DESC] LIMIT n
302
    // columns for orderby keys
303
    std::vector<uint32_t> _orderby_key_columns;
304
    BaseTabletSPtr _tablet;
305
    RowsetReaderContext _reader_context;
306
    TabletSchemaSPtr _tablet_schema;
307
    KeysParam _keys_param;
308
    std::vector<bool> _is_lower_keys_included;
309
    std::vector<bool> _is_upper_keys_included;
310
    std::vector<std::shared_ptr<ColumnPredicate>> _col_predicates;
311
    std::vector<std::shared_ptr<ColumnPredicate>> _value_col_predicates;
312
    DeleteHandler _delete_handler;
313
314
    // Indicates whether the tablets has do a aggregation in storage engine.
315
    bool _aggregation = false;
316
    // for agg query, we don't need to finalize when scan agg object data
317
    ReaderType _reader_type = ReaderType::READER_QUERY;
318
    bool _delete_sign_available = false;
319
    bool _filter_delete = false;
320
    bool _direct_mode = false;
321
322
    uint64_t _merged_rows = 0;
323
    OlapReaderStatistics _stats;
324
};
325
326
} // namespace doris