Coverage Report

Created: 2026-08-27 01:19

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
55
    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
51
    virtual ~Scanner() {
66
51
        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_state->query_mem_tracker());
67
51
        _input_block.clear();
68
51
        _conjuncts.clear();
69
51
        _projections.clear();
70
51
        _origin_block.clear();
71
51
        _common_expr_ctxs_push_down.clear();
72
51
        DorisMetrics::instance()->scanner_cnt->increment(-1);
73
51
    }
74
75
    virtual Status init(RuntimeState* state, const VExprContextSPtrs& conjuncts);
76
5
    Status prepare() {
77
5
        SCOPED_RAW_TIMER(&_per_scanner_timer);
78
5
        SCOPED_RAW_TIMER(&_per_scanner_prepare_timer);
79
5
        return _prepare_impl();
80
5
    }
81
82
2
    Status open(RuntimeState* state) {
83
2
        SCOPED_RAW_TIMER(&_per_scanner_timer);
84
2
        SCOPED_RAW_TIMER(&_per_scanner_open_timer);
85
2
        return _open_impl(state);
86
2
    }
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
0
    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
2
    virtual Status _open_impl(RuntimeState* state) {
121
2
        _block_avg_bytes = state->batch_size() * 8;
122
2
        return Status::OK();
123
2
    }
124
125
    // Subclass should implement this to return data.
126
    virtual Status _get_block_impl(RuntimeState* state, Block* block, bool* eof) = 0;
127
128
0
    virtual bool _can_merge_padding_blocks(const Block& /*left*/, const Block& /*right*/) const {
129
0
        return true;
130
0
    }
131
132
2
    Status _merge_padding_block() {
133
2
        if (_padding_block.empty()) {
134
1
            _padding_block.swap(_origin_block);
135
1
        } else if (_origin_block.rows()) {
136
1
            ScopedMutableBlock scoped_mutable_block(&_padding_block);
137
1
            auto& mutable_block = scoped_mutable_block.mutable_block();
138
1
            RETURN_IF_ERROR(mutable_block.merge(_origin_block));
139
1
        }
140
2
        return Status::OK();
141
2
    }
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
2
    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
6
    void _start_scan_cpu_timer() {
165
6
        _cpu_watch.reset();
166
6
        _cpu_watch.start();
167
6
    }
168
169
6
    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
6
    void start_wait_worker_timer() {
176
6
        _watch.reset();
177
6
        _watch.start();
178
6
    }
179
180
6
    void resume() {
181
6
        _update_wait_worker_timer();
182
6
        _start_scan_cpu_timer();
183
6
    }
184
6
    void pause() {
185
6
        _update_scan_cpu_timer();
186
6
        start_wait_worker_timer();
187
6
    }
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
9
    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
6
    virtual void update_realtime_counters() {}
204
205
342
    RuntimeState* runtime_state() { return _state; }
206
207
12
    bool is_open() const { return _is_open; }
208
2
    void set_opened() { _is_open = true; }
209
210
0
    virtual doris::TabletStorageType get_storage_type() {
211
0
        return doris::TabletStorageType::STORAGE_TYPE_REMOTE;
212
0
    }
213
214
    // Returns true if this scanner's scan range has been pruned by a runtime filter.
215
0
    virtual bool is_pruned_by_runtime_filter() const { return false; }
216
217
    // Releases resources owned by a scanner that runtime-filter pruning makes unnecessary before
218
    // open(). The scanner will not be scheduled again after this call.
219
6
    virtual void release_unopened_resources() {
220
6
        DORIS_CHECK(!_is_open);
221
6
        _has_prepared = false;
222
6
    }
223
224
0
    bool need_to_close() const { return _need_to_close; }
225
226
4
    void mark_to_need_to_close() {
227
        // If the scanner is failed during init or open, then not need update counters
228
        // because the query is fail and the counter is useless. And it may core during
229
        // update counters. For example, update counters depend on scanner's tablet, but
230
        // the tablet == null when init failed.
231
4
        if (_is_open) {
232
0
            _collect_profile_before_close();
233
0
        }
234
4
        _need_to_close = true;
235
4
    }
236
237
0
    void set_status_on_failure(const Status& st) { _status = st; }
238
239
6
    int64_t limit() const { return _limit; }
240
241
0
    auto get_block_avg_bytes() const { return _block_avg_bytes; }
242
243
2
    void update_block_avg_bytes(size_t block_avg_bytes) { _block_avg_bytes = block_avg_bytes; }
244
245
protected:
246
    RuntimeState* _state = nullptr;
247
    ScanLocalStateBase* _local_state = nullptr;
248
249
    // Set if scan node has sort limit info
250
    int64_t _limit = -1;
251
252
    RuntimeProfile* _profile = nullptr;
253
254
    const TupleDescriptor* _output_tuple_desc = nullptr;
255
    std::optional<std::reference_wrapper<const RowDescriptor>> _projection_output_row_descriptor;
256
    bool _has_projection = false;
257
258
    // If _input_tuple_desc is set, the scanner will read data into
259
    // this _input_block first, then convert to the output block.
260
    Block _input_block;
261
262
    bool _is_open = false;
263
    std::atomic<bool> _is_closed {false};
264
    bool _need_to_close = false;
265
    Status _status;
266
267
    // If _applied_rf_num == _total_rf_num
268
    // means all runtime filters are arrived and applied.
269
    int _applied_rf_num = 0;
270
    int _total_rf_num = 0;
271
    // Cloned from _conjuncts of scan node.
272
    // It includes predicate in SQL and runtime filters.
273
    VExprContextSPtrs _conjuncts;
274
    VExprContextSPtrs _projections;
275
    // Used in common subexpression elimination to compute intermediate results.
276
    std::vector<VExprContextSPtrs> _intermediate_projections;
277
    Block _origin_block;
278
    Block _padding_block;
279
280
    VExprContextSPtrs _common_expr_ctxs_push_down;
281
282
    // num of rows read from scanner
283
    int64_t _num_rows_read = 0;
284
285
    int64_t _num_byte_read = 0;
286
287
    // num of rows return from scanner, after filter block
288
    int64_t _num_rows_return = 0;
289
290
    size_t _block_avg_bytes = 0;
291
292
    // Set true after counter is updated finally
293
    bool _has_updated_counter = false;
294
295
    // watch to count the time wait for scanner thread
296
    MonotonicStopWatch _watch;
297
    // Do not use ScopedTimer. There is no guarantee that, the counter
298
    ThreadCpuStopWatch _cpu_watch;
299
    int64_t _scanner_wait_worker_timer = 0;
300
    int64_t _scan_cpu_timer = 0;
301
302
    bool _is_load = false;
303
304
    bool _has_prepared = false;
305
306
    ScannerCounter _counter;
307
    int64_t _per_scanner_timer = 0;
308
    int64_t _per_scanner_prepare_timer = 0;
309
    int64_t _per_scanner_open_timer = 0;
310
    int64_t _projection_timer = 0;
311
312
    bool _should_stop = false;
313
314
    // Cached pointer to ScanOperator's remaining-limit counter. Null when
315
    // this scanner is on the topn path or the query has no LIMIT.
316
    std::atomic<int64_t>* _shared_scan_limit = nullptr;
317
};
318
319
using ScannerSPtr = std::shared_ptr<Scanner>;
320
321
} // namespace doris