Coverage Report

Created: 2026-08-21 09:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/scan/scanner.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 <stdint.h>
21
22
#include <algorithm>
23
#include <atomic>
24
#include <functional>
25
#include <optional>
26
#include <vector>
27
28
#include "common/status.h"
29
#include "core/block/block.h"
30
#include "runtime/exec_env.h"
31
#include "runtime/runtime_state.h"
32
#include "storage/tablet/tablet.h"
33
#include "util/stopwatch.hpp"
34
35
namespace doris {
36
class RuntimeProfile;
37
class TupleDescriptor;
38
39
class VExprContext;
40
41
class ScanLocalStateBase;
42
} // namespace doris
43
44
namespace doris {
45
46
// Counter for load
47
struct ScannerCounter {
48
21.1k
    ScannerCounter() : num_rows_filtered(0), num_rows_unselected(0) {}
49
50
    int64_t num_rows_filtered;   // unqualified rows (unmatched the dest schema, or no partition)
51
    int64_t num_rows_unselected; // rows filtered by predicates
52
};
53
54
class Scanner {
55
public:
56
    Scanner(RuntimeState* state, ScanLocalStateBase* local_state, int64_t limit,
57
            RuntimeProfile* profile);
58
59
    //only used for FileScanner read one line.
60
    Scanner(RuntimeState* state, RuntimeProfile* profile)
61
19
            : _state(state), _limit(1), _profile(profile), _total_rf_num(0), _has_prepared(false) {
62
19
        DorisMetrics::instance()->scanner_cnt->increment(1);
63
19
    };
64
65
21.1k
    virtual ~Scanner() {
66
21.1k
        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_state->query_mem_tracker());
67
21.1k
        _input_block.clear();
68
21.1k
        _conjuncts.clear();
69
21.1k
        _projections.clear();
70
21.1k
        _origin_block.clear();
71
21.1k
        _common_expr_ctxs_push_down.clear();
72
21.1k
        DorisMetrics::instance()->scanner_cnt->increment(-1);
73
21.1k
    }
74
75
    virtual Status init(RuntimeState* state, const VExprContextSPtrs& conjuncts);
76
21.1k
    Status prepare() {
77
21.1k
        SCOPED_RAW_TIMER(&_per_scanner_timer);
78
21.1k
        SCOPED_RAW_TIMER(&_per_scanner_prepare_timer);
79
21.1k
        return _prepare_impl();
80
21.1k
    }
81
82
21.1k
    Status open(RuntimeState* state) {
83
21.1k
        SCOPED_RAW_TIMER(&_per_scanner_timer);
84
21.1k
        SCOPED_RAW_TIMER(&_per_scanner_open_timer);
85
21.1k
        return _open_impl(state);
86
21.1k
    }
87
88
    Status get_block(RuntimeState* state, Block* block, bool* eos);
89
    Status get_block_after_projects(RuntimeState* state, Block* block, bool* eos);
90
91
    virtual Status close(RuntimeState* state);
92
93
    // Try to stop scanner, and all running readers.
94
21.1k
    virtual void try_stop() { _should_stop = true; };
95
96
0
    virtual std::string get_name() { return ""; }
97
98
    // return the readable name of current scan range.
99
    // eg, for file scanner, return the current file path.
100
0
    virtual std::string get_current_scan_range_name() { return "not implemented"; }
101
102
#ifdef BE_TEST
103
    static uint64_t TEST_build_condition_cache_digest(uint64_t seed,
104
                                                      const VExprContextSPtrs& conjuncts);
105
#endif
106
107
protected:
108
    // Rebuild the condition-cache digest from the scanner's current conjunct snapshot. The local
109
    // state's digest is used only as a safety gate: zero means condition cache was disabled during
110
    // scan-node open (for example by TopN or an expression without a reliable digest).
111
    uint64_t _current_condition_cache_digest() const;
112
    static uint64_t _build_condition_cache_digest(uint64_t seed,
113
                                                  const VExprContextSPtrs& conjuncts);
114
115
6
    virtual Status _prepare_impl() {
116
6
        _has_prepared = true;
117
6
        return Status::OK();
118
6
    }
119
120
21.1k
    virtual Status _open_impl(RuntimeState* state) {
121
21.1k
        _block_avg_bytes = state->batch_size() * 8;
122
21.1k
        return Status::OK();
123
21.1k
    }
124
125
    // Subclass should implement this to return data.
126
    virtual Status _get_block_impl(RuntimeState* state, Block* block, bool* eof) = 0;
127
128
20.9k
    virtual bool _can_merge_padding_blocks(const Block& /*left*/, const Block& /*right*/) const {
129
20.9k
        return true;
130
20.9k
    }
131
132
26.0k
    Status _merge_padding_block() {
133
26.0k
        if (_padding_block.empty()) {
134
20.9k
            _padding_block.swap(_origin_block);
135
20.9k
        } else if (_origin_block.rows()) {
136
273
            ScopedMutableBlock scoped_mutable_block(&_padding_block);
137
273
            auto& mutable_block = scoped_mutable_block.mutable_block();
138
273
            RETURN_IF_ERROR(mutable_block.merge(_origin_block));
139
273
        }
140
26.0k
        return Status::OK();
141
26.0k
    }
142
143
    // Update the counters before closing this scanner
144
    virtual void _collect_profile_before_close();
145
146
    // Whether rows filtered/unselected by this scanner should be reported to the load
147
    // counters in RuntimeState. Only the scanner reading the load source data should
148
    // report, otherwise rows filtered by query predicates (e.g. in INSERT INTO ... SELECT
149
    // or DELETE FROM ... WHERE) would be mixed into load counters and make
150
    // num_rows_load_success() negative.
151
21.1k
    virtual bool _should_update_load_counters() const { return _is_load; }
152
153
    // Check if scanner is already closed, if not, mark it as closed.
154
    // Returns true if the scanner was successfully marked as closed (first time).
155
    // Returns false if the scanner was already closed.
156
    bool _try_close();
157
158
    // Filter the output block finally.
159
    virtual Status _filter_output_block(Block* block);
160
161
    Status _do_projections(Block* origin_block, Block* output_block);
162
163
private:
164
21.2k
    void _start_scan_cpu_timer() {
165
21.2k
        _cpu_watch.reset();
166
21.2k
        _cpu_watch.start();
167
21.2k
    }
168
169
21.2k
    void _update_wait_worker_timer() { _scanner_wait_worker_timer += _watch.elapsed_time(); }
170
    void _update_scan_cpu_timer();
171
172
public:
173
    // Call start_wait_worker_timer() when submit the scanner to the thread pool.
174
    // And call update_wait_worker_timer() when it is actually being executed.
175
42.4k
    void start_wait_worker_timer() {
176
42.4k
        _watch.reset();
177
42.4k
        _watch.start();
178
42.4k
    }
179
180
21.2k
    void resume() {
181
21.2k
        _update_wait_worker_timer();
182
21.2k
        _start_scan_cpu_timer();
183
21.2k
    }
184
21.2k
    void pause() {
185
21.2k
        _update_scan_cpu_timer();
186
21.2k
        start_wait_worker_timer();
187
21.2k
    }
188
0
    int64_t get_time_cost_ns() const { return _per_scanner_timer; }
189
0
    int64_t get_prepare_time_cost_ns() const { return _per_scanner_prepare_timer; }
190
0
    int64_t get_open_time_cost_ns() const { return _per_scanner_open_timer; }
191
192
0
    int64_t projection_time() const { return _projection_timer; }
193
0
    int64_t get_rows_read() const { return _num_rows_read; }
194
195
21.2k
    bool has_prepared() const { return _has_prepared; }
196
197
    Status try_append_late_arrival_runtime_filter();
198
199
0
    int64_t get_scanner_wait_worker_timer() const { return _scanner_wait_worker_timer; }
200
201
    // Some counters need to be updated realtime, for example, workload group policy need
202
    // scan bytes to cancel the query exceed limit.
203
0
    virtual void update_realtime_counters() {}
204
205
42.5k
    RuntimeState* runtime_state() { return _state; }
206
207
21.2k
    bool is_open() const { return _is_open; }
208
21.1k
    void set_opened() { _is_open = true; }
209
210
12
    virtual doris::TabletStorageType get_storage_type() {
211
12
        return doris::TabletStorageType::STORAGE_TYPE_REMOTE;
212
12
    }
213
214
    // Returns true if this scanner's partition has been pruned by a runtime filter.
215
    // Overridden by OlapScanner to check partition pruning state.
216
24
    virtual bool check_partition_pruned() const { return false; }
217
218
0
    bool need_to_close() const { return _need_to_close; }
219
220
21.1k
    void mark_to_need_to_close() {
221
        // If the scanner is failed during init or open, then not need update counters
222
        // because the query is fail and the counter is useless. And it may core during
223
        // update counters. For example, update counters depend on scanner's tablet, but
224
        // the tablet == null when init failed.
225
21.1k
        if (_is_open) {
226
21.1k
            _collect_profile_before_close();
227
21.1k
        }
228
21.1k
        _need_to_close = true;
229
21.1k
    }
230
231
0
    void set_status_on_failure(const Status& st) { _status = st; }
232
233
21.2k
    int64_t limit() const { return _limit; }
234
235
0
    auto get_block_avg_bytes() const { return _block_avg_bytes; }
236
237
4.93k
    void update_block_avg_bytes(size_t block_avg_bytes) { _block_avg_bytes = block_avg_bytes; }
238
239
protected:
240
    RuntimeState* _state = nullptr;
241
    ScanLocalStateBase* _local_state = nullptr;
242
243
    // Set if scan node has sort limit info
244
    int64_t _limit = -1;
245
246
    RuntimeProfile* _profile = nullptr;
247
248
    const TupleDescriptor* _output_tuple_desc = nullptr;
249
    std::optional<std::reference_wrapper<const RowDescriptor>> _projection_output_row_descriptor;
250
    bool _has_projection = false;
251
252
    // If _input_tuple_desc is set, the scanner will read data into
253
    // this _input_block first, then convert to the output block.
254
    Block _input_block;
255
256
    bool _is_open = false;
257
    std::atomic<bool> _is_closed {false};
258
    bool _need_to_close = false;
259
    Status _status;
260
261
    // If _applied_rf_num == _total_rf_num
262
    // means all runtime filters are arrived and applied.
263
    int _applied_rf_num = 0;
264
    int _total_rf_num = 0;
265
    // Cloned from _conjuncts of scan node.
266
    // It includes predicate in SQL and runtime filters.
267
    VExprContextSPtrs _conjuncts;
268
    VExprContextSPtrs _projections;
269
    // Used in common subexpression elimination to compute intermediate results.
270
    std::vector<VExprContextSPtrs> _intermediate_projections;
271
    Block _origin_block;
272
    Block _padding_block;
273
274
    VExprContextSPtrs _common_expr_ctxs_push_down;
275
276
    // num of rows read from scanner
277
    int64_t _num_rows_read = 0;
278
279
    int64_t _num_byte_read = 0;
280
281
    // num of rows return from scanner, after filter block
282
    int64_t _num_rows_return = 0;
283
284
    size_t _block_avg_bytes = 0;
285
286
    // Set true after counter is updated finally
287
    bool _has_updated_counter = false;
288
289
    // watch to count the time wait for scanner thread
290
    MonotonicStopWatch _watch;
291
    // Do not use ScopedTimer. There is no guarantee that, the counter
292
    ThreadCpuStopWatch _cpu_watch;
293
    int64_t _scanner_wait_worker_timer = 0;
294
    int64_t _scan_cpu_timer = 0;
295
296
    bool _is_load = false;
297
298
    bool _has_prepared = false;
299
300
    ScannerCounter _counter;
301
    int64_t _per_scanner_timer = 0;
302
    int64_t _per_scanner_prepare_timer = 0;
303
    int64_t _per_scanner_open_timer = 0;
304
    int64_t _projection_timer = 0;
305
306
    bool _should_stop = false;
307
308
    // Cached pointer to ScanOperator's remaining-limit counter. Null when
309
    // this scanner is on the topn path or the query has no LIMIT.
310
    std::atomic<int64_t>* _shared_scan_limit = nullptr;
311
};
312
313
using ScannerSPtr = std::shared_ptr<Scanner>;
314
315
} // namespace doris