Coverage Report

Created: 2026-05-13 21:59

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
18
        : _state(state),
39
18
          _local_state(local_state),
40
18
          _limit(limit),
41
18
          _profile(profile),
42
18
          _output_tuple_desc(_local_state->output_tuple_desc()),
43
18
          _output_row_descriptor(_local_state->_parent->output_row_descriptor()),
44
18
          _has_prepared(false) {
45
18
    _total_rf_num = cast_set<int>(_local_state->_helper.runtime_filter_nums());
46
18
    DorisMetrics::instance()->scanner_cnt->increment(1);
47
18
}
48
49
3
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
3
    _shared_scan_limit = _local_state->shared_scan_limit_ptr();
55
56
3
    if (!conjuncts.empty()) {
57
0
        _conjuncts.resize(conjuncts.size());
58
0
        for (size_t i = 0; i != conjuncts.size(); ++i) {
59
0
            RETURN_IF_ERROR(conjuncts[i]->clone(state, _conjuncts[i]));
60
0
        }
61
0
    }
62
63
3
    const auto& projections = _local_state->_projections;
64
3
    if (!projections.empty()) {
65
0
        _projections.resize(projections.size());
66
0
        for (size_t i = 0; i != projections.size(); ++i) {
67
0
            RETURN_IF_ERROR(projections[i]->clone(state, _projections[i]));
68
0
        }
69
0
    }
70
71
3
    const auto& intermediate_projections = _local_state->_intermediate_projections;
72
3
    if (!intermediate_projections.empty()) {
73
0
        _intermediate_projections.resize(intermediate_projections.size());
74
0
        for (int i = 0; i < intermediate_projections.size(); i++) {
75
0
            _intermediate_projections[i].resize(intermediate_projections[i].size());
76
0
            for (int j = 0; j < intermediate_projections[i].size(); j++) {
77
0
                RETURN_IF_ERROR(intermediate_projections[i][j]->clone(
78
0
                        state, _intermediate_projections[i][j]));
79
0
            }
80
0
        }
81
0
    }
82
83
3
    return Status::OK();
84
3
}
85
86
0
Status Scanner::get_block_after_projects(RuntimeState* state, Block* block, bool* eos) {
87
0
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().vscanner_get_block);
88
0
    auto& row_descriptor = _local_state->_parent->row_descriptor();
89
0
    if (_output_row_descriptor) {
90
0
        if (_alreay_eos) {
91
0
            *eos = true;
92
0
            _padding_block.swap(_origin_block);
93
0
        } else {
94
0
            _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
95
0
            const auto min_batch_size = std::max(state->batch_size() / 2, 1);
96
0
            const auto block_max_bytes = state->preferred_block_size_bytes();
97
0
            while (_padding_block.rows() < min_batch_size &&
98
0
                   _padding_block.bytes() < block_max_bytes && !*eos) {
99
0
                RETURN_IF_ERROR(get_block(state, &_origin_block, eos));
100
0
                if (_origin_block.rows() >= min_batch_size) {
101
0
                    break;
102
0
                }
103
104
0
                if (_origin_block.rows() + _padding_block.rows() <= state->batch_size() &&
105
0
                    _origin_block.bytes() + _padding_block.bytes() <= block_max_bytes) {
106
0
                    RETURN_IF_ERROR(_merge_padding_block());
107
0
                    _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
108
0
                } else {
109
0
                    if (_origin_block.rows() < _padding_block.rows()) {
110
0
                        _padding_block.swap(_origin_block);
111
0
                    }
112
0
                    break;
113
0
                }
114
0
            }
115
0
        }
116
117
        // first output the origin block change eos = false, next time output padding block
118
        // set the eos to true
119
0
        if (*eos && !_padding_block.empty() && !_origin_block.empty()) {
120
0
            _alreay_eos = true;
121
0
            *eos = false;
122
0
        }
123
0
        if (_origin_block.empty() && !_padding_block.empty()) {
124
0
            _padding_block.swap(_origin_block);
125
0
        }
126
0
        return _do_projections(&_origin_block, block);
127
0
    } else {
128
0
        return get_block(state, block, eos);
129
0
    }
130
0
}
131
132
1
Status Scanner::get_block(RuntimeState* state, Block* block, bool* eof) {
133
    // only empty block should be here
134
1
    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
1
    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
1
    SCOPED_RAW_TIMER(&_per_scanner_timer);
146
1
    int64_t rows_read_threshold = _num_rows_read + config::doris_scanner_row_num;
147
1
    if (!block->mem_reuse()) {
148
3
        for (auto* const slot_desc : _output_tuple_desc->slots()) {
149
3
            block->insert(ColumnWithTypeAndName(slot_desc->get_empty_mutable_column(),
150
3
                                                slot_desc->get_data_type_ptr(),
151
3
                                                slot_desc->col_name()));
152
3
        }
153
1
    }
154
155
1
    {
156
1
        do {
157
            // 1. Get input block from scanner
158
1
            {
159
                // get block time
160
1
                SCOPED_TIMER(_local_state->_scan_timer);
161
1
                RETURN_IF_ERROR(_get_block_impl(state, block, eof));
162
0
                if (*eof) {
163
0
                    DCHECK(block->rows() == 0);
164
0
                    break;
165
0
                }
166
0
                _num_rows_read += block->rows();
167
0
                _num_byte_read += block->allocated_bytes();
168
0
            }
169
170
            // 2. Filter the output block finally.
171
0
            {
172
0
                SCOPED_TIMER(_local_state->_filter_timer);
173
0
                RETURN_IF_ERROR(_filter_output_block(block));
174
0
            }
175
            // record rows return (after filter) for _limit check
176
0
            _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
0
            if (_shared_scan_limit && block->rows() > 0) {
182
0
                _shared_scan_limit->fetch_sub(block->rows(), std::memory_order_acq_rel);
183
0
            }
184
0
        } while (!_should_stop && !state->is_cancelled() && block->rows() == 0 && !(*eof) &&
185
0
                 _num_rows_read < rows_read_threshold);
186
1
    }
187
188
0
    if (state->is_cancelled()) {
189
        // TODO: Should return the specific ErrorStatus instead of just Cancelled.
190
0
        return Status::Cancelled("cancelled");
191
0
    }
192
0
    *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
0
    *eof = *eof || (_limit > 0 && _num_rows_return >= _limit);
196
0
    *eof = *eof || (_shared_scan_limit && _shared_scan_limit->load(std::memory_order_acquire) <= 0);
197
198
0
    return Status::OK();
199
0
}
200
201
0
Status Scanner::_filter_output_block(Block* block) {
202
0
    auto old_rows = block->rows();
203
0
    Status st = VExprContext::filter_block(_conjuncts, block, block->columns());
204
0
    _counter.num_rows_unselected += old_rows - block->rows();
205
0
    return st;
206
0
}
207
208
0
Status Scanner::_do_projections(Block* origin_block, Block* output_block) {
209
0
    SCOPED_RAW_TIMER(&_per_scanner_timer);
210
0
    SCOPED_RAW_TIMER(&_projection_timer);
211
212
0
    const size_t rows = origin_block->rows();
213
0
    if (rows == 0) {
214
0
        return Status::OK();
215
0
    }
216
0
    Block input_block = *origin_block;
217
218
0
    std::vector<int> result_column_ids;
219
0
    for (auto& projections : _intermediate_projections) {
220
0
        result_column_ids.resize(projections.size());
221
0
        for (int i = 0; i < projections.size(); i++) {
222
0
            RETURN_IF_ERROR(projections[i]->execute(&input_block, &result_column_ids[i]));
223
0
        }
224
0
        input_block.shuffle_columns(result_column_ids);
225
0
    }
226
227
0
    DCHECK_EQ(rows, input_block.rows());
228
0
    MutableBlock mutable_block =
229
0
            VectorizedUtils::build_mutable_mem_reuse_block(output_block, *_output_row_descriptor);
230
231
0
    auto& mutable_columns = mutable_block.mutable_columns();
232
233
0
    DCHECK_EQ(mutable_columns.size(), _projections.size());
234
235
0
    for (int i = 0; i < mutable_columns.size(); ++i) {
236
0
        ColumnPtr column_ptr;
237
0
        RETURN_IF_ERROR(_projections[i]->execute(&input_block, column_ptr));
238
0
        column_ptr = column_ptr->convert_to_full_column_if_const();
239
0
        if (mutable_columns[i]->is_nullable() != column_ptr->is_nullable()) {
240
0
            throw Exception(ErrorCode::INTERNAL_ERROR, "Nullable mismatch");
241
0
        }
242
0
        mutable_columns[i] = column_ptr->assume_mutable();
243
0
    }
244
245
0
    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
0
    auto empty_columns = origin_block->clone_empty_columns();
249
0
    origin_block->set_columns(std::move(empty_columns));
250
0
    DCHECK_EQ(output_block->rows(), rows);
251
252
0
    return Status::OK();
253
0
}
254
255
2
Status Scanner::try_append_late_arrival_runtime_filter() {
256
2
    if (_applied_rf_num == _total_rf_num) {
257
1
        return Status::OK();
258
1
    }
259
2
    DCHECK(_applied_rf_num < _total_rf_num);
260
1
    int arrived_rf_num = 0;
261
1
    RETURN_IF_ERROR(_local_state->update_late_arrival_runtime_filter(_state, arrived_rf_num));
262
263
1
    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
1
    _conjuncts.clear();
270
1
    RETURN_IF_ERROR(_local_state->clone_conjunct_ctxs(_conjuncts));
271
1
    _applied_rf_num = arrived_rf_num;
272
1
    return Status::OK();
273
1
}
274
275
17
Status Scanner::close(RuntimeState* state) {
276
#ifndef BE_TEST
277
    COUNTER_UPDATE(_local_state->_scanner_wait_worker_timer, _scanner_wait_worker_timer);
278
#endif
279
17
    return Status::OK();
280
17
}
281
282
167
bool Scanner::_try_close() {
283
167
    bool expected = false;
284
167
    return _is_closed.compare_exchange_strong(expected, true);
285
167
}
286
287
0
void Scanner::_collect_profile_before_close() {
288
0
    COUNTER_UPDATE(_local_state->_scan_cpu_timer, _scan_cpu_timer);
289
0
    COUNTER_UPDATE(_local_state->_rows_read_counter, _num_rows_read);
290
291
    // Update stats for load
292
0
    _state->update_num_rows_load_filtered(_counter.num_rows_filtered);
293
0
    _state->update_num_rows_load_unselected(_counter.num_rows_unselected);
294
0
}
295
296
0
void Scanner::_update_scan_cpu_timer() {
297
0
    int64_t cpu_time = _cpu_watch.elapsed_time();
298
0
    _scan_cpu_timer += cpu_time;
299
0
    if (_state && _state->get_query_ctx()) {
300
0
        _state->get_query_ctx()->resource_ctx()->cpu_context()->update_cpu_cost_ms(cpu_time);
301
0
    }
302
0
}
303
304
} // namespace doris