Coverage Report

Created: 2026-05-18 17:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/scan/scanner.cpp
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
#include "exec/scan/scanner.h"
19
20
#include <glog/logging.h>
21
22
#include "common/config.h"
23
#include "common/status.h"
24
#include "core/block/column_with_type_and_name.h"
25
#include "core/column/column_nothing.h"
26
#include "exec/operator/scan_operator.h"
27
#include "exec/scan/scan_node.h"
28
#include "exprs/vexpr_context.h"
29
#include "runtime/descriptors.h"
30
#include "runtime/runtime_profile.h"
31
#include "util/concurrency_stats.h"
32
#include "util/defer_op.h"
33
34
namespace doris {
35
36
Scanner::Scanner(RuntimeState* state, ScanLocalStateBase* local_state, int64_t limit,
37
                 RuntimeProfile* profile)
38
422k
        : _state(state),
39
422k
          _local_state(local_state),
40
422k
          _limit(limit),
41
422k
          _profile(profile),
42
422k
          _output_tuple_desc(_local_state->output_tuple_desc()),
43
422k
          _output_row_descriptor(_local_state->_parent->output_row_descriptor()),
44
422k
          _has_prepared(false) {
45
422k
    _total_rf_num = cast_set<int>(_local_state->_helper.runtime_filter_nums());
46
422k
    DorisMetrics::instance()->scanner_cnt->increment(1);
47
422k
}
48
49
422k
Status Scanner::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
50
    // All scanners share a remaining-limit counter so a LIMIT query can
51
    // stop once enough rows have been collected across scanners.
52
    // Key TopN scans have no ordinary scan LIMIT, so each scanner can
53
    // independently produce its full local top-N.
54
422k
    _shared_scan_limit = _local_state->shared_scan_limit_ptr();
55
56
422k
    if (!conjuncts.empty()) {
57
35.3k
        _conjuncts.resize(conjuncts.size());
58
84.5k
        for (size_t i = 0; i != conjuncts.size(); ++i) {
59
49.1k
            RETURN_IF_ERROR(conjuncts[i]->clone(state, _conjuncts[i]));
60
49.1k
        }
61
35.3k
    }
62
63
422k
    const auto& projections = _local_state->_projections;
64
422k
    if (!projections.empty()) {
65
379k
        _projections.resize(projections.size());
66
5.21M
        for (size_t i = 0; i != projections.size(); ++i) {
67
4.83M
            RETURN_IF_ERROR(projections[i]->clone(state, _projections[i]));
68
4.83M
        }
69
379k
    }
70
71
422k
    const auto& intermediate_projections = _local_state->_intermediate_projections;
72
422k
    if (!intermediate_projections.empty()) {
73
2.33k
        _intermediate_projections.resize(intermediate_projections.size());
74
13.8k
        for (int i = 0; i < intermediate_projections.size(); i++) {
75
11.4k
            _intermediate_projections[i].resize(intermediate_projections[i].size());
76
69.2k
            for (int j = 0; j < intermediate_projections[i].size(); j++) {
77
57.7k
                RETURN_IF_ERROR(intermediate_projections[i][j]->clone(
78
57.7k
                        state, _intermediate_projections[i][j]));
79
57.7k
            }
80
11.4k
        }
81
2.33k
    }
82
83
422k
    return Status::OK();
84
422k
}
85
86
472k
Status Scanner::get_block_after_projects(RuntimeState* state, Block* block, bool* eos) {
87
472k
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().vscanner_get_block);
88
472k
    auto& row_descriptor = _local_state->_parent->row_descriptor();
89
472k
    if (_output_row_descriptor) {
90
395k
        if (_alreay_eos) {
91
0
            *eos = true;
92
0
            _padding_block.swap(_origin_block);
93
395k
        } else {
94
395k
            _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
95
395k
            const auto min_batch_size = std::max(state->batch_size() / 2, 1);
96
395k
            const auto block_max_bytes = state->preferred_block_size_bytes();
97
846k
            while (_padding_block.rows() < min_batch_size &&
98
846k
                   _padding_block.bytes() < block_max_bytes && !*eos) {
99
465k
                RETURN_IF_ERROR(get_block(state, &_origin_block, eos));
100
465k
                if (_origin_block.rows() >= min_batch_size) {
101
14.4k
                    break;
102
14.4k
                }
103
104
450k
                if (_origin_block.rows() + _padding_block.rows() <= state->batch_size() &&
105
450k
                    _origin_block.bytes() + _padding_block.bytes() <= block_max_bytes) {
106
450k
                    RETURN_IF_ERROR(_merge_padding_block());
107
450k
                    _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
108
450k
                } else {
109
64
                    if (_origin_block.rows() < _padding_block.rows()) {
110
0
                        _padding_block.swap(_origin_block);
111
0
                    }
112
64
                    break;
113
64
                }
114
450k
            }
115
395k
        }
116
117
        // first output the origin block change eos = false, next time output padding block
118
        // set the eos to true
119
395k
        if (*eos && !_padding_block.empty() && !_origin_block.empty()) {
120
0
            _alreay_eos = true;
121
0
            *eos = false;
122
0
        }
123
395k
        if (_origin_block.empty() && !_padding_block.empty()) {
124
35.7k
            _padding_block.swap(_origin_block);
125
35.7k
        }
126
395k
        return _do_projections(&_origin_block, block);
127
395k
    } else {
128
77.3k
        return get_block(state, block, eos);
129
77.3k
    }
130
472k
}
131
132
542k
Status Scanner::get_block(RuntimeState* state, Block* block, bool* eof) {
133
    // only empty block should be here
134
542k
    DCHECK(block->rows() == 0);
135
136
    // Stop early if other scanners have already collected enough rows
137
    // for the SQL LIMIT. Skipped when _shared_scan_limit is null (topn
138
    // path or no LIMIT).
139
542k
    if (_shared_scan_limit && _shared_scan_limit->load(std::memory_order_acquire) <= 0) {
140
0
        *eof = true;
141
0
        return Status::OK();
142
0
    }
143
144
    // scanner running time
145
542k
    SCOPED_RAW_TIMER(&_per_scanner_timer);
146
542k
    int64_t rows_read_threshold = _num_rows_read + config::doris_scanner_row_num;
147
542k
    if (!block->mem_reuse()) {
148
5.30M
        for (auto* const slot_desc : _output_tuple_desc->slots()) {
149
5.30M
            block->insert(ColumnWithTypeAndName(slot_desc->get_empty_mutable_column(),
150
5.30M
                                                slot_desc->get_data_type_ptr(),
151
5.30M
                                                slot_desc->col_name()));
152
5.30M
        }
153
414k
    }
154
155
542k
    {
156
654k
        do {
157
            // 1. Get input block from scanner
158
654k
            {
159
                // get block time
160
654k
                SCOPED_TIMER(_local_state->_scan_timer);
161
654k
                RETURN_IF_ERROR(_get_block_impl(state, block, eof));
162
654k
                if (*eof) {
163
422k
                    DCHECK(block->rows() == 0);
164
422k
                    break;
165
422k
                }
166
231k
                _num_rows_read += block->rows();
167
231k
                _num_byte_read += block->allocated_bytes();
168
231k
            }
169
170
            // 2. Filter the output block finally.
171
0
            {
172
231k
                SCOPED_TIMER(_local_state->_filter_timer);
173
231k
                RETURN_IF_ERROR(_filter_output_block(block));
174
231k
            }
175
            // record rows return (after filter) for _limit check
176
231k
            _num_rows_return += block->rows();
177
            // Publish progress to the shared counter so peer scanners can
178
            // observe it. The counter may go negative when several scanners
179
            // subtract concurrently; that is harmless because the operator's
180
            // reached_limit() makes the final cut.
181
231k
            if (_shared_scan_limit && block->rows() > 0) {
182
2.30k
                _shared_scan_limit->fetch_sub(block->rows(), std::memory_order_acq_rel);
183
2.30k
            }
184
231k
        } while (!_should_stop && !state->is_cancelled() && block->rows() == 0 && !(*eof) &&
185
231k
                 _num_rows_read < rows_read_threshold);
186
542k
    }
187
188
542k
    if (state->is_cancelled()) {
189
        // TODO: Should return the specific ErrorStatus instead of just Cancelled.
190
4
        return Status::Cancelled("cancelled");
191
4
    }
192
542k
    *eof = *eof || _should_stop;
193
    // set eof to true if per scanner limit is reached
194
    // currently for query: ORDER BY key LIMIT n
195
542k
    *eof = *eof || (_limit > 0 && _num_rows_return >= _limit);
196
542k
    *eof = *eof || (_shared_scan_limit && _shared_scan_limit->load(std::memory_order_acquire) <= 0);
197
198
542k
    return Status::OK();
199
542k
}
200
201
231k
Status Scanner::_filter_output_block(Block* block) {
202
231k
    auto old_rows = block->rows();
203
231k
    Status st = VExprContext::filter_block(_conjuncts, block, block->columns());
204
231k
    _counter.num_rows_unselected += old_rows - block->rows();
205
231k
    return st;
206
231k
}
207
208
395k
Status Scanner::_do_projections(Block* origin_block, Block* output_block) {
209
395k
    SCOPED_RAW_TIMER(&_per_scanner_timer);
210
395k
    SCOPED_RAW_TIMER(&_projection_timer);
211
212
395k
    const size_t rows = origin_block->rows();
213
395k
    if (rows == 0) {
214
345k
        return Status::OK();
215
345k
    }
216
50.0k
    Block input_block = *origin_block;
217
218
50.0k
    std::vector<int> result_column_ids;
219
50.0k
    for (auto& projections : _intermediate_projections) {
220
16.4k
        result_column_ids.resize(projections.size());
221
125k
        for (int i = 0; i < projections.size(); i++) {
222
108k
            RETURN_IF_ERROR(projections[i]->execute(&input_block, &result_column_ids[i]));
223
108k
        }
224
16.4k
        input_block.shuffle_columns(result_column_ids);
225
16.4k
    }
226
227
50.0k
    DCHECK_EQ(rows, input_block.rows());
228
50.0k
    MutableBlock mutable_block =
229
50.0k
            VectorizedUtils::build_mutable_mem_reuse_block(output_block, *_output_row_descriptor);
230
231
50.0k
    auto& mutable_columns = mutable_block.mutable_columns();
232
233
50.0k
    DCHECK_EQ(mutable_columns.size(), _projections.size());
234
235
219k
    for (int i = 0; i < mutable_columns.size(); ++i) {
236
168k
        ColumnPtr column_ptr;
237
168k
        RETURN_IF_ERROR(_projections[i]->execute(&input_block, column_ptr));
238
168k
        column_ptr = column_ptr->convert_to_full_column_if_const();
239
168k
        if (mutable_columns[i]->is_nullable() != column_ptr->is_nullable()) {
240
0
            throw Exception(ErrorCode::INTERNAL_ERROR, "Nullable mismatch");
241
0
        }
242
168k
        mutable_columns[i] = column_ptr->assume_mutable();
243
168k
    }
244
245
50.0k
    output_block->set_columns(std::move(mutable_columns));
246
247
    // origin columns was moved into output_block, so we need to set origin_block to empty columns
248
50.0k
    auto empty_columns = origin_block->clone_empty_columns();
249
50.0k
    origin_block->set_columns(std::move(empty_columns));
250
50.0k
    DCHECK_EQ(output_block->rows(), rows);
251
252
50.0k
    return Status::OK();
253
50.0k
}
254
255
472k
Status Scanner::try_append_late_arrival_runtime_filter() {
256
472k
    if (_applied_rf_num == _total_rf_num) {
257
470k
        return Status::OK();
258
470k
    }
259
472k
    DCHECK(_applied_rf_num < _total_rf_num);
260
2.75k
    int arrived_rf_num = 0;
261
2.75k
    RETURN_IF_ERROR(_local_state->update_late_arrival_runtime_filter(_state, arrived_rf_num));
262
263
2.75k
    if (arrived_rf_num == _applied_rf_num) {
264
        // No newly arrived runtime filters, just return;
265
0
        return Status::OK();
266
0
    }
267
268
    // avoid conjunct destroy in used by storage layer
269
2.75k
    _conjuncts.clear();
270
2.75k
    RETURN_IF_ERROR(_local_state->clone_conjunct_ctxs(_conjuncts));
271
2.75k
    _applied_rf_num = arrived_rf_num;
272
2.75k
    return Status::OK();
273
2.75k
}
274
275
423k
Status Scanner::close(RuntimeState* state) {
276
423k
#ifndef BE_TEST
277
423k
    COUNTER_UPDATE(_local_state->_scanner_wait_worker_timer, _scanner_wait_worker_timer);
278
423k
#endif
279
423k
    return Status::OK();
280
423k
}
281
282
423k
bool Scanner::_try_close() {
283
423k
    bool expected = false;
284
423k
    return _is_closed.compare_exchange_strong(expected, true);
285
423k
}
286
287
422k
void Scanner::_collect_profile_before_close() {
288
422k
    COUNTER_UPDATE(_local_state->_scan_cpu_timer, _scan_cpu_timer);
289
422k
    COUNTER_UPDATE(_local_state->_rows_read_counter, _num_rows_read);
290
291
    // Update stats for load
292
422k
    _state->update_num_rows_load_filtered(_counter.num_rows_filtered);
293
422k
    _state->update_num_rows_load_unselected(_counter.num_rows_unselected);
294
422k
}
295
296
472k
void Scanner::_update_scan_cpu_timer() {
297
472k
    int64_t cpu_time = _cpu_watch.elapsed_time();
298
472k
    _scan_cpu_timer += cpu_time;
299
472k
    if (_state && _state->get_query_ctx()) {
300
472k
        _state->get_query_ctx()->resource_ctx()->cpu_context()->update_cpu_cost_ms(cpu_time);
301
472k
    }
302
472k
}
303
304
} // namespace doris