Coverage Report

Created: 2026-10-20 04:48

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
1.99k
    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
21
            : _state(state), _limit(1), _profile(profile), _total_rf_num(0), _has_prepared(false) {
62
21
        DorisMetrics::instance()->scanner_cnt->increment(1);
63
21
    };
64
65
90
    virtual ~Scanner() {
66
90
        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_state->query_mem_tracker());
67
90
        _input_block.clear();
68
90
        _conjuncts.clear();
69
90
        _projections.clear();
70
90
        _origin_block.clear();
71
90
        _common_expr_ctxs_push_down.clear();
72
90
        DorisMetrics::instance()->scanner_cnt->increment(-1);
73
90
    }
74
75
    virtual Status init(RuntimeState* state, const VExprContextSPtrs& conjuncts);
76
8
    Status prepare() {
77
8
        SCOPED_RAW_TIMER(&_per_scanner_timer);
78
8
        SCOPED_RAW_TIMER(&_per_scanner_prepare_timer);
79
8
        return _prepare_impl();
80
8
    }
81
82
5
    Status open(RuntimeState* state) {
83
5
        SCOPED_RAW_TIMER(&_per_scanner_timer);
84
5
        SCOPED_RAW_TIMER(&_per_scanner_open_timer);
85
5
        return _open_impl(state);
86
5
    }
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
9
    virtual Status _prepare_impl() {
116
9
        _has_prepared = true;
117
9
        return Status::OK();
118
9
    }
119
120
5
    virtual Status _open_impl(RuntimeState* state) {
121
5
        _block_avg_bytes = state->batch_size() * 8;
122
5
        return Status::OK();
123
5
    }
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
14
    Status _merge_padding_block() {
133
14
        if (_padding_block.empty()) {
134
7
            _padding_block.swap(_origin_block);
135
7
        } else if (_origin_block.rows()) {
136
6
            ScopedMutableBlock scoped_mutable_block(&_padding_block);
137
6
            auto& mutable_block = scoped_mutable_block.mutable_block();
138
6
            RETURN_IF_ERROR(mutable_block.merge(_origin_block));
139
6
        }
140
14
        return Status::OK();
141
14
    }
142
143
    // True once scanners of this operator have produced the whole shared LIMIT. The scanner then
144
    // stops reading but does not report EOS for it: EOS means the underlying read is exhausted,
145
    // while the LIMIT is applied by the scan operator, which stops the scanners once it holds
146
    // enough rows.
147
63
    bool _shared_scan_limit_exhausted() const {
148
63
        return _shared_scan_limit != nullptr &&
149
63
               _shared_scan_limit->load(std::memory_order_acquire) <= 0;
150
63
    }
151
152
    // Update the counters before closing this scanner
153
    virtual void _collect_profile_before_close();
154
155
    // Whether rows filtered/unselected by this scanner should be reported to the load
156
    // counters in RuntimeState. Only the scanner reading the load source data should
157
    // report, otherwise rows filtered by query predicates (e.g. in INSERT INTO ... SELECT
158
    // or DELETE FROM ... WHERE) would be mixed into load counters and make
159
    // num_rows_load_success() negative.
160
2
    virtual bool _should_update_load_counters() const { return _is_load; }
161
162
    // Check if scanner is already closed, if not, mark it as closed.
163
    // Returns true if the scanner was successfully marked as closed (first time).
164
    // Returns false if the scanner was already closed.
165
    bool _try_close();
166
167
    // Filter the output block finally.
168
    virtual Status _filter_output_block(Block* block);
169
170
    Status _do_projections(Block* origin_block, Block* output_block);
171
172
private:
173
21
    void _start_scan_cpu_timer() {
174
21
        _cpu_watch.reset();
175
21
        _cpu_watch.start();
176
21
    }
177
178
21
    void _update_wait_worker_timer() { _scanner_wait_worker_timer += _watch.elapsed_time(); }
179
    void _update_scan_cpu_timer();
180
181
public:
182
    // Call start_wait_worker_timer() when submit the scanner to the thread pool.
183
    // And call update_wait_worker_timer() when it is actually being executed.
184
44
    void start_wait_worker_timer() {
185
44
        _watch.reset();
186
44
        _watch.start();
187
44
    }
188
189
21
    void resume() {
190
21
        _update_wait_worker_timer();
191
21
        _start_scan_cpu_timer();
192
21
    }
193
21
    void pause() {
194
21
        _update_scan_cpu_timer();
195
21
        start_wait_worker_timer();
196
21
    }
197
0
    int64_t get_time_cost_ns() const { return _per_scanner_timer; }
198
0
    int64_t get_prepare_time_cost_ns() const { return _per_scanner_prepare_timer; }
199
0
    int64_t get_open_time_cost_ns() const { return _per_scanner_open_timer; }
200
201
0
    int64_t projection_time() const { return _projection_timer; }
202
0
    int64_t get_rows_read() const { return _num_rows_read; }
203
204
24
    bool has_prepared() const { return _has_prepared; }
205
206
    Status try_append_late_arrival_runtime_filter();
207
208
0
    int64_t get_scanner_wait_worker_timer() const { return _scanner_wait_worker_timer; }
209
210
    // Some counters need to be updated realtime, for example, workload group policy need
211
    // scan bytes to cancel the query exceed limit.
212
21
    virtual void update_realtime_counters() {}
213
214
458
    RuntimeState* runtime_state() { return _state; }
215
216
42
    bool is_open() const { return _is_open; }
217
5
    void set_opened() { _is_open = true; }
218
219
0
    virtual doris::TabletStorageType get_storage_type() {
220
0
        return doris::TabletStorageType::STORAGE_TYPE_REMOTE;
221
0
    }
222
223
    // Returns true if this scanner's scan range has been pruned by a runtime filter.
224
33
    virtual bool is_pruned_by_runtime_filter() const { return false; }
225
226
    // Releases resources owned by a scanner that runtime-filter pruning makes unnecessary before
227
    // open(). The scanner will not be scheduled again after this call.
228
6
    virtual void release_unopened_resources() {
229
6
        DORIS_CHECK(!_is_open);
230
6
        _has_prepared = false;
231
6
    }
232
233
0
    bool need_to_close() const { return _need_to_close; }
234
235
7
    void mark_to_need_to_close() {
236
        // If the scanner is failed during init or open, then not need update counters
237
        // because the query is fail and the counter is useless. And it may core during
238
        // update counters. For example, update counters depend on scanner's tablet, but
239
        // the tablet == null when init failed.
240
7
        if (_is_open) {
241
3
            _collect_profile_before_close();
242
3
        }
243
7
        _need_to_close = true;
244
7
    }
245
246
0
    void set_status_on_failure(const Status& st) { _status = st; }
247
248
21
    int64_t limit() const { return _limit; }
249
250
0
    auto get_block_avg_bytes() const { return _block_avg_bytes; }
251
252
14
    void update_block_avg_bytes(size_t block_avg_bytes) { _block_avg_bytes = block_avg_bytes; }
253
254
protected:
255
    RuntimeState* _state = nullptr;
256
    ScanLocalStateBase* _local_state = nullptr;
257
258
    // Set if scan node has sort limit info
259
    int64_t _limit = -1;
260
261
    RuntimeProfile* _profile = nullptr;
262
263
    const TupleDescriptor* _output_tuple_desc = nullptr;
264
    std::optional<std::reference_wrapper<const RowDescriptor>> _projection_output_row_descriptor;
265
    bool _has_projection = false;
266
267
    // If _input_tuple_desc is set, the scanner will read data into
268
    // this _input_block first, then convert to the output block.
269
    Block _input_block;
270
271
    bool _is_open = false;
272
    std::atomic<bool> _is_closed {false};
273
    bool _need_to_close = false;
274
    Status _status;
275
276
    // If _applied_rf_num == _total_rf_num
277
    // means all runtime filters are arrived and applied.
278
    int _applied_rf_num = 0;
279
    int _total_rf_num = 0;
280
    // Cloned from _conjuncts of scan node.
281
    // It includes predicate in SQL and runtime filters.
282
    VExprContextSPtrs _conjuncts;
283
    VExprContextSPtrs _projections;
284
    // Used in common subexpression elimination to compute intermediate results.
285
    std::vector<VExprContextSPtrs> _intermediate_projections;
286
    Block _origin_block;
287
    Block _padding_block;
288
289
    VExprContextSPtrs _common_expr_ctxs_push_down;
290
291
    // num of rows read from scanner
292
    int64_t _num_rows_read = 0;
293
294
    int64_t _num_byte_read = 0;
295
296
    // num of rows return from scanner, after filter block
297
    int64_t _num_rows_return = 0;
298
299
    size_t _block_avg_bytes = 0;
300
301
    // Set true after counter is updated finally
302
    bool _has_updated_counter = false;
303
304
    // watch to count the time wait for scanner thread
305
    MonotonicStopWatch _watch;
306
    // Do not use ScopedTimer. There is no guarantee that, the counter
307
    ThreadCpuStopWatch _cpu_watch;
308
    int64_t _scanner_wait_worker_timer = 0;
309
    int64_t _scan_cpu_timer = 0;
310
311
    bool _is_load = false;
312
313
    bool _has_prepared = false;
314
315
    ScannerCounter _counter;
316
    int64_t _per_scanner_timer = 0;
317
    int64_t _per_scanner_prepare_timer = 0;
318
    int64_t _per_scanner_open_timer = 0;
319
    int64_t _projection_timer = 0;
320
321
    bool _should_stop = false;
322
323
    // Cached pointer to ScanOperator's remaining-limit counter. Null when
324
    // this scanner is on the topn path or the query has no LIMIT.
325
    std::atomic<int64_t>* _shared_scan_limit = nullptr;
326
};
327
328
using ScannerSPtr = std::shared_ptr<Scanner>;
329
330
} // namespace doris