Coverage Report

Created: 2026-06-09 15:03

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
1.10M
        : _state(state),
39
1.10M
          _local_state(local_state),
40
1.10M
          _limit(limit),
41
1.10M
          _profile(profile),
42
1.10M
          _output_tuple_desc(_local_state->output_tuple_desc()),
43
1.10M
          _output_row_descriptor(_local_state->_parent->output_row_descriptor()),
44
1.10M
          _has_prepared(false) {
45
1.10M
    _total_rf_num = cast_set<int>(_local_state->_helper.runtime_filter_nums());
46
1.10M
    DorisMetrics::instance()->scanner_cnt->increment(1);
47
1.10M
}
48
49
1.10M
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
1.10M
    _shared_scan_limit = _local_state->shared_scan_limit_ptr();
55
56
1.10M
    if (!conjuncts.empty()) {
57
24.9k
        _conjuncts.resize(conjuncts.size());
58
58.2k
        for (size_t i = 0; i != conjuncts.size(); ++i) {
59
33.2k
            RETURN_IF_ERROR(conjuncts[i]->clone(state, _conjuncts[i]));
60
33.2k
        }
61
24.9k
    }
62
63
1.10M
    const auto& projections = _local_state->_projections;
64
1.10M
    if (!projections.empty()) {
65
1.01M
        _projections.resize(projections.size());
66
10.4M
        for (size_t i = 0; i != projections.size(); ++i) {
67
9.47M
            RETURN_IF_ERROR(projections[i]->clone(state, _projections[i]));
68
9.47M
        }
69
1.01M
    }
70
71
1.10M
    const auto& intermediate_projections = _local_state->_intermediate_projections;
72
1.10M
    if (!intermediate_projections.empty()) {
73
12.5k
        _intermediate_projections.resize(intermediate_projections.size());
74
34.1k
        for (int i = 0; i < intermediate_projections.size(); i++) {
75
21.6k
            _intermediate_projections[i].resize(intermediate_projections[i].size());
76
128k
            for (int j = 0; j < intermediate_projections[i].size(); j++) {
77
107k
                RETURN_IF_ERROR(intermediate_projections[i][j]->clone(
78
107k
                        state, _intermediate_projections[i][j]));
79
107k
            }
80
21.6k
        }
81
12.5k
    }
82
83
1.10M
    return Status::OK();
84
1.10M
}
85
86
1.17M
Status Scanner::get_block_after_projects(RuntimeState* state, Block* block, bool* eos) {
87
1.17M
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().vscanner_get_block);
88
1.17M
    auto& row_descriptor = _local_state->_parent->row_descriptor();
89
1.17M
    if (_output_row_descriptor) {
90
1.03M
        _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
91
1.03M
        const auto min_batch_size = std::max(state->batch_size() / 2, 1);
92
1.03M
        const auto block_max_bytes = state->preferred_block_size_bytes();
93
1.31M
        while (_padding_block.rows() < min_batch_size && _padding_block.bytes() < block_max_bytes &&
94
1.31M
               !*eos) {
95
1.31M
            RETURN_IF_ERROR(get_block(state, &_origin_block, eos));
96
1.31M
            if (*eos) {
97
                // For the final block, merge any padding directly and return eos in this call.
98
                // The merged tail can be larger than the target batch, but each source block is
99
                // already bounded by the lower scanner.
100
1.01M
                RETURN_IF_ERROR(_merge_padding_block());
101
1.01M
                _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
102
1.01M
                break;
103
1.01M
            }
104
302k
            if (_origin_block.rows() >= min_batch_size) {
105
23.4k
                break;
106
23.4k
            }
107
108
278k
            if (_origin_block.rows() + _padding_block.rows() <= state->batch_size() &&
109
278k
                _origin_block.bytes() + _padding_block.bytes() <= block_max_bytes) {
110
278k
                RETURN_IF_ERROR(_merge_padding_block());
111
278k
                _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
112
278k
            } else {
113
425
                if (_origin_block.rows() < _padding_block.rows()) {
114
0
                    _padding_block.swap(_origin_block);
115
0
                }
116
425
                break;
117
425
            }
118
278k
        }
119
120
1.03M
        if (_origin_block.empty() && !_padding_block.empty()) {
121
210k
            _padding_block.swap(_origin_block);
122
210k
        }
123
1.03M
        return _do_projections(&_origin_block, block);
124
1.03M
    } else {
125
135k
        return get_block(state, block, eos);
126
135k
    }
127
1.17M
}
128
129
1.45M
Status Scanner::get_block(RuntimeState* state, Block* block, bool* eof) {
130
    // only empty block should be here
131
1.45M
    DCHECK(block->rows() == 0);
132
133
    // Stop early if other scanners have already collected enough rows
134
    // for the SQL LIMIT. Skipped when _shared_scan_limit is null (topn
135
    // path or no LIMIT).
136
1.45M
    if (_shared_scan_limit && _shared_scan_limit->load(std::memory_order_acquire) <= 0) {
137
14
        *eof = true;
138
14
        return Status::OK();
139
14
    }
140
141
    // scanner running time
142
1.45M
    SCOPED_RAW_TIMER(&_per_scanner_timer);
143
1.45M
    int64_t rows_read_threshold = _num_rows_read + config::doris_scanner_row_num;
144
1.45M
    if (!block->mem_reuse()) {
145
10.6M
        for (auto* const slot_desc : _output_tuple_desc->slots()) {
146
10.6M
            block->insert(ColumnWithTypeAndName(slot_desc->get_empty_mutable_column(),
147
10.6M
                                                slot_desc->get_data_type_ptr(),
148
10.6M
                                                slot_desc->col_name()));
149
10.6M
        }
150
1.22M
    }
151
152
1.45M
    {
153
1.51M
        do {
154
            // 1. Get input block from scanner
155
1.51M
            {
156
                // get block time
157
1.51M
                SCOPED_TIMER(_local_state->_scan_timer);
158
1.51M
                RETURN_IF_ERROR(_get_block_impl(state, block, eof));
159
1.51M
                if (*eof) {
160
1.09M
                    DCHECK(block->rows() == 0);
161
1.09M
                    break;
162
1.09M
                }
163
418k
                _num_rows_read += block->rows();
164
418k
                _num_byte_read += block->allocated_bytes();
165
418k
            }
166
167
            // 2. Filter the output block finally.
168
0
            {
169
418k
                SCOPED_TIMER(_local_state->_filter_timer);
170
418k
                RETURN_IF_ERROR(_filter_output_block(block));
171
418k
            }
172
            // record rows return (after filter) for _limit check
173
418k
            _num_rows_return += block->rows();
174
            // Publish progress to the shared counter so peer scanners can
175
            // observe it. The counter may go negative when several scanners
176
            // subtract concurrently; that is harmless because the operator's
177
            // reached_limit() makes the final cut.
178
418k
            if (_shared_scan_limit && block->rows() > 0) {
179
1.64k
                _shared_scan_limit->fetch_sub(block->rows(), std::memory_order_acq_rel);
180
1.64k
            }
181
418k
        } while (!_should_stop && !state->is_cancelled() && block->rows() == 0 && !(*eof) &&
182
418k
                 _num_rows_read < rows_read_threshold);
183
1.45M
    }
184
185
1.45M
    if (state->is_cancelled()) {
186
        // TODO: Should return the specific ErrorStatus instead of just Cancelled.
187
12
        return Status::Cancelled("cancelled");
188
12
    }
189
1.45M
    *eof = *eof || _should_stop;
190
    // set eof to true if per scanner limit is reached
191
    // currently for query: ORDER BY key LIMIT n
192
1.45M
    *eof = *eof || (_limit > 0 && _num_rows_return >= _limit);
193
1.45M
    *eof = *eof || (_shared_scan_limit && _shared_scan_limit->load(std::memory_order_acquire) <= 0);
194
195
1.45M
    return Status::OK();
196
1.45M
}
197
198
416k
Status Scanner::_filter_output_block(Block* block) {
199
416k
    auto old_rows = block->rows();
200
416k
    Status st = VExprContext::filter_block(_conjuncts, block, block->columns(),
201
416k
                                           ScanFilterStage::EXEC_RESIDUAL);
202
416k
    _counter.num_rows_unselected += old_rows - block->rows();
203
416k
    return st;
204
416k
}
205
206
1.03M
Status Scanner::_do_projections(Block* origin_block, Block* output_block) {
207
1.03M
    SCOPED_RAW_TIMER(&_per_scanner_timer);
208
1.03M
    SCOPED_RAW_TIMER(&_projection_timer);
209
210
1.03M
    const size_t rows = origin_block->rows();
211
1.03M
    if (rows == 0) {
212
803k
        return Status::OK();
213
803k
    }
214
234k
    Block input_block = *origin_block;
215
216
234k
    std::vector<int> result_column_ids;
217
234k
    for (auto& projections : _intermediate_projections) {
218
34.1k
        result_column_ids.resize(projections.size());
219
229k
        for (int i = 0; i < projections.size(); i++) {
220
195k
            RETURN_IF_ERROR(projections[i]->execute(&input_block, &result_column_ids[i]));
221
195k
        }
222
34.1k
        input_block.shuffle_columns(result_column_ids);
223
34.1k
    }
224
225
234k
    DCHECK_EQ(rows, input_block.rows());
226
234k
    auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
227
234k
            output_block, *_output_row_descriptor);
228
234k
    auto& mutable_block = scoped_mutable_block.mutable_block();
229
230
234k
    auto& mutable_columns = mutable_block.mutable_columns();
231
232
234k
    DCHECK_EQ(mutable_columns.size(), _projections.size());
233
234
871k
    for (int i = 0; i < mutable_columns.size(); ++i) {
235
638k
        ColumnPtr column_ptr;
236
638k
        RETURN_IF_ERROR(_projections[i]->execute(&input_block, column_ptr));
237
637k
        column_ptr = column_ptr->convert_to_full_column_if_const();
238
637k
        if (mutable_columns[i]->is_nullable() != column_ptr->is_nullable()) {
239
0
            throw Exception(ErrorCode::INTERNAL_ERROR, "Nullable mismatch");
240
0
        }
241
637k
        mutable_columns[i] = IColumn::mutate(std::move(column_ptr));
242
637k
    }
243
244
233k
    scoped_mutable_block.restore();
245
246
    // origin columns was moved into output_block, so we need to set origin_block to empty columns
247
233k
    auto empty_columns = origin_block->clone_empty_columns();
248
233k
    origin_block->set_columns(std::move(empty_columns));
249
233k
    DCHECK_EQ(output_block->rows(), rows);
250
251
233k
    return Status::OK();
252
234k
}
253
254
1.17M
Status Scanner::try_append_late_arrival_runtime_filter() {
255
1.17M
    if (_applied_rf_num == _total_rf_num) {
256
1.13M
        return Status::OK();
257
1.13M
    }
258
1.17M
    DCHECK(_applied_rf_num < _total_rf_num);
259
37.1k
    int arrived_rf_num = 0;
260
37.1k
    RETURN_IF_ERROR(_local_state->update_late_arrival_runtime_filter(_state, arrived_rf_num));
261
262
37.1k
    if (arrived_rf_num == _applied_rf_num) {
263
        // No newly arrived runtime filters, just return;
264
490
        return Status::OK();
265
490
    }
266
267
    // avoid conjunct destroy in used by storage layer
268
36.6k
    _conjuncts.clear();
269
36.6k
    RETURN_IF_ERROR(_local_state->clone_conjunct_ctxs(_conjuncts));
270
36.6k
    _applied_rf_num = arrived_rf_num;
271
36.6k
    return Status::OK();
272
36.6k
}
273
274
1.10M
Status Scanner::close(RuntimeState* state) {
275
1.10M
#ifndef BE_TEST
276
1.10M
    COUNTER_UPDATE(_local_state->_scanner_wait_worker_timer, _scanner_wait_worker_timer);
277
1.10M
#endif
278
1.10M
    return Status::OK();
279
1.10M
}
280
281
1.10M
bool Scanner::_try_close() {
282
1.10M
    bool expected = false;
283
1.10M
    return _is_closed.compare_exchange_strong(expected, true);
284
1.10M
}
285
286
1.09M
void Scanner::_collect_profile_before_close() {
287
1.09M
    COUNTER_UPDATE(_local_state->_scan_cpu_timer, _scan_cpu_timer);
288
1.09M
    COUNTER_UPDATE(_local_state->_rows_read_counter, _num_rows_read);
289
290
    // Update stats for load
291
1.09M
    _state->update_num_rows_load_filtered(_counter.num_rows_filtered);
292
1.09M
    _state->update_num_rows_load_unselected(_counter.num_rows_unselected);
293
1.09M
}
294
295
1.17M
void Scanner::_update_scan_cpu_timer() {
296
1.17M
    int64_t cpu_time = _cpu_watch.elapsed_time();
297
1.17M
    _scan_cpu_timer += cpu_time;
298
1.17M
    if (_state && _state->get_query_ctx()) {
299
1.17M
        _state->get_query_ctx()->resource_ctx()->cpu_context()->update_cpu_cost_ms(cpu_time);
300
1.17M
    }
301
1.17M
}
302
303
} // namespace doris