Coverage Report

Created: 2026-07-23 14:51

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 <iterator>
23
24
#include "common/config.h"
25
#include "common/status.h"
26
#include "core/block/column_with_type_and_name.h"
27
#include "core/column/column_nothing.h"
28
#include "exec/operator/scan_operator.h"
29
#include "exec/scan/scan_node.h"
30
#include "exprs/vexpr_context.h"
31
#include "runtime/descriptors.h"
32
#include "runtime/runtime_profile.h"
33
#include "util/concurrency_stats.h"
34
#include "util/defer_op.h"
35
36
namespace doris {
37
38
Scanner::Scanner(RuntimeState* state, ScanLocalStateBase* local_state, int64_t limit,
39
                 RuntimeProfile* profile)
40
1.42M
        : _state(state),
41
1.42M
          _local_state(local_state),
42
1.42M
          _limit(limit),
43
1.42M
          _profile(profile),
44
1.42M
          _output_tuple_desc(_local_state->output_tuple_desc()),
45
1.42M
          _output_row_descriptor(_local_state->_parent->output_row_descriptor()),
46
1.42M
          _has_prepared(false) {
47
1.42M
    _total_rf_num = cast_set<int>(_local_state->_helper.runtime_filter_nums());
48
1.42M
    DorisMetrics::instance()->scanner_cnt->increment(1);
49
1.42M
}
50
51
1.42M
Status Scanner::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
52
    // All scanners share a remaining-limit counter so a LIMIT query can
53
    // stop once enough rows have been collected across scanners.
54
    // Key TopN scans have no ordinary scan LIMIT, so each scanner can
55
    // independently produce its full local top-N.
56
1.42M
    _shared_scan_limit = _local_state->shared_scan_limit_ptr();
57
58
1.42M
    if (!conjuncts.empty()) {
59
46.0k
        _conjuncts.resize(conjuncts.size());
60
108k
        for (size_t i = 0; i != conjuncts.size(); ++i) {
61
62.4k
            RETURN_IF_ERROR(conjuncts[i]->clone(state, _conjuncts[i]));
62
62.4k
        }
63
46.0k
    }
64
65
1.42M
    const auto& projections = _local_state->_projections;
66
1.42M
    if (!projections.empty()) {
67
1.31M
        _projections.resize(projections.size());
68
13.8M
        for (size_t i = 0; i != projections.size(); ++i) {
69
12.5M
            RETURN_IF_ERROR(projections[i]->clone(state, _projections[i]));
70
12.5M
        }
71
1.31M
    }
72
73
1.42M
    const auto& intermediate_projections = _local_state->_intermediate_projections;
74
1.42M
    if (!intermediate_projections.empty()) {
75
15.1k
        _intermediate_projections.resize(intermediate_projections.size());
76
49.7k
        for (int i = 0; i < intermediate_projections.size(); i++) {
77
34.6k
            _intermediate_projections[i].resize(intermediate_projections[i].size());
78
206k
            for (int j = 0; j < intermediate_projections[i].size(); j++) {
79
171k
                RETURN_IF_ERROR(intermediate_projections[i][j]->clone(
80
171k
                        state, _intermediate_projections[i][j]));
81
171k
            }
82
34.6k
        }
83
15.1k
    }
84
85
1.42M
    return Status::OK();
86
1.42M
}
87
88
1.53M
Status Scanner::get_block_after_projects(RuntimeState* state, Block* block, bool* eos) {
89
1.53M
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().vscanner_get_block);
90
1.53M
    auto& row_descriptor = _local_state->_parent->row_descriptor();
91
1.53M
    if (_output_row_descriptor) {
92
1.35M
        _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
93
1.35M
        const auto min_batch_size = std::max(state->batch_size() / 2, 1);
94
1.35M
        const auto block_max_bytes = state->preferred_block_size_bytes();
95
1.74M
        while (_padding_block.rows() < min_batch_size && _padding_block.bytes() < block_max_bytes &&
96
1.74M
               !*eos) {
97
1.73M
            RETURN_IF_ERROR(get_block(state, &_origin_block, eos));
98
1.73M
            if (*eos) {
99
                // For the final block, merge any padding directly and return eos in this call.
100
                // The merged tail can be larger than the target batch, but each source block is
101
                // already bounded by the lower scanner.
102
1.31M
                RETURN_IF_ERROR(_merge_padding_block());
103
1.31M
                _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
104
1.31M
                break;
105
1.31M
            }
106
419k
            if (_origin_block.rows() >= min_batch_size) {
107
33.3k
                break;
108
33.3k
            }
109
110
386k
            if (_origin_block.rows() + _padding_block.rows() <= state->batch_size() &&
111
386k
                _origin_block.bytes() + _padding_block.bytes() <= block_max_bytes) {
112
386k
                RETURN_IF_ERROR(_merge_padding_block());
113
386k
                _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
114
18.4E
            } else {
115
18.4E
                if (_origin_block.rows() < _padding_block.rows()) {
116
0
                    _padding_block.swap(_origin_block);
117
0
                }
118
18.4E
                break;
119
18.4E
            }
120
386k
        }
121
122
1.35M
        if (_origin_block.empty() && !_padding_block.empty()) {
123
261k
            _padding_block.swap(_origin_block);
124
261k
        }
125
1.35M
        return _do_projections(&_origin_block, block);
126
1.35M
    } else {
127
183k
        return get_block(state, block, eos);
128
183k
    }
129
1.53M
}
130
131
1.91M
Status Scanner::get_block(RuntimeState* state, Block* block, bool* eof) {
132
    // only empty block should be here
133
1.91M
    DCHECK(block->rows() == 0);
134
135
    // Stop early if other scanners have already collected enough rows
136
    // for the SQL LIMIT. Skipped when _shared_scan_limit is null (topn
137
    // path or no LIMIT).
138
1.91M
    if (_shared_scan_limit && _shared_scan_limit->load(std::memory_order_acquire) <= 0) {
139
29
        *eof = true;
140
29
        return Status::OK();
141
29
    }
142
143
    // scanner running time
144
1.91M
    SCOPED_RAW_TIMER(&_per_scanner_timer);
145
1.91M
    int64_t rows_read_threshold = _num_rows_read + config::doris_scanner_row_num;
146
1.91M
    if (!block->mem_reuse()) {
147
14.1M
        for (auto* const slot_desc : _output_tuple_desc->slots()) {
148
14.1M
            block->insert(ColumnWithTypeAndName(slot_desc->get_empty_mutable_column(),
149
14.1M
                                                slot_desc->get_data_type_ptr(),
150
14.1M
                                                slot_desc->col_name()));
151
14.1M
        }
152
1.57M
    }
153
154
1.91M
    {
155
2.00M
        do {
156
            // 1. Get input block from scanner
157
2.00M
            {
158
                // get block time
159
2.00M
                SCOPED_TIMER(_local_state->_scan_timer);
160
2.00M
                RETURN_IF_ERROR(_get_block_impl(state, block, eof));
161
2.00M
                if (*eof) {
162
1.42M
                    DCHECK(block->rows() == 0);
163
1.42M
                    break;
164
1.42M
                }
165
                // Some scanners apply owned predicates before returning the block. Account the
166
                // materialized input, not only survivors, so the per-turn progress bound remains
167
                // effective for highly selective predicates.
168
581k
                _num_rows_read += _last_block_rows_read(*block);
169
581k
                _num_byte_read += _last_block_bytes_read(*block);
170
581k
            }
171
172
            // 2. Filter the output block finally.
173
0
            {
174
581k
                SCOPED_TIMER(_local_state->_filter_timer);
175
581k
                RETURN_IF_ERROR(_filter_output_block(block));
176
581k
            }
177
            // record rows return (after filter) for _limit check
178
581k
            _num_rows_return += block->rows();
179
            // Publish progress to the shared counter so peer scanners can
180
            // observe it. The counter may go negative when several scanners
181
            // subtract concurrently; that is harmless because the operator's
182
            // reached_limit() makes the final cut.
183
581k
            if (_shared_scan_limit && block->rows() > 0) {
184
3.18k
                _shared_scan_limit->fetch_sub(block->rows(), std::memory_order_acq_rel);
185
3.18k
            }
186
582k
        } while (!_should_stop && !state->is_cancelled() && block->rows() == 0 && !(*eof) &&
187
581k
                 _num_rows_read < rows_read_threshold);
188
1.91M
    }
189
190
1.91M
    if (state->is_cancelled()) {
191
        // TODO: Should return the specific ErrorStatus instead of just Cancelled.
192
13
        return Status::Cancelled("cancelled");
193
13
    }
194
1.91M
    *eof = *eof || _should_stop;
195
    // set eof to true if per scanner limit is reached
196
    // currently for query: ORDER BY key LIMIT n
197
1.91M
    *eof = *eof || (_limit > 0 && _num_rows_return >= _limit);
198
1.91M
    *eof = *eof || (_shared_scan_limit && _shared_scan_limit->load(std::memory_order_acquire) <= 0);
199
200
1.91M
    return Status::OK();
201
1.91M
}
202
203
443k
Status Scanner::_filter_output_block(Block* block) {
204
443k
    auto old_rows = block->rows();
205
443k
    Status st = VExprContext::filter_block(_conjuncts, block, block->columns());
206
443k
    _counter.num_rows_unselected += old_rows - block->rows();
207
443k
    return st;
208
443k
}
209
210
1.35M
Status Scanner::_do_projections(Block* origin_block, Block* output_block) {
211
1.35M
    SCOPED_RAW_TIMER(&_per_scanner_timer);
212
1.35M
    SCOPED_RAW_TIMER(&_projection_timer);
213
214
1.35M
    const size_t rows = origin_block->rows();
215
1.35M
    if (rows == 0) {
216
1.06M
        return Status::OK();
217
1.06M
    }
218
294k
    Block input_block = *origin_block;
219
220
294k
    std::vector<int> result_column_ids;
221
294k
    for (auto& projections : _intermediate_projections) {
222
46.0k
        result_column_ids.resize(projections.size());
223
323k
        for (int i = 0; i < projections.size(); i++) {
224
277k
            RETURN_IF_ERROR(projections[i]->execute(&input_block, &result_column_ids[i]));
225
277k
        }
226
45.9k
        input_block.shuffle_columns(result_column_ids);
227
45.9k
    }
228
229
294k
    DCHECK_EQ(rows, input_block.rows());
230
294k
    auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
231
294k
            output_block, *_output_row_descriptor);
232
294k
    auto& mutable_block = scoped_mutable_block.mutable_block();
233
234
294k
    auto& mutable_columns = mutable_block.mutable_columns();
235
236
294k
    DCHECK_EQ(mutable_columns.size(), _projections.size());
237
238
1.07M
    for (int i = 0; i < mutable_columns.size(); ++i) {
239
780k
        ColumnPtr column_ptr;
240
780k
        RETURN_IF_ERROR(_projections[i]->execute(&input_block, column_ptr));
241
779k
        column_ptr = column_ptr->convert_to_full_column_if_const();
242
779k
        if (mutable_columns[i]->is_nullable() != column_ptr->is_nullable()) {
243
0
            throw Exception(ErrorCode::INTERNAL_ERROR, "Nullable mismatch");
244
0
        }
245
779k
        mutable_columns[i] = IColumn::mutate(std::move(column_ptr));
246
779k
    }
247
248
292k
    scoped_mutable_block.restore();
249
250
    // origin columns was moved into output_block, so we need to set origin_block to empty columns
251
292k
    auto empty_columns = origin_block->clone_empty_columns();
252
292k
    origin_block->set_columns(std::move(empty_columns));
253
292k
    DCHECK_EQ(output_block->rows(), rows);
254
255
292k
    return Status::OK();
256
294k
}
257
258
1.53M
Status Scanner::try_append_late_arrival_runtime_filter() {
259
1.53M
    if (_applied_rf_num == _total_rf_num) {
260
1.49M
        return Status::OK();
261
1.49M
    }
262
1.53M
    DCHECK(_applied_rf_num < _total_rf_num);
263
45.8k
    int arrived_rf_num = 0;
264
45.8k
    VExprContextSPtrs arrived_conjuncts;
265
45.8k
    RETURN_IF_ERROR(_local_state->update_late_arrival_runtime_filter(
266
45.8k
            _state, _applied_rf_num, arrived_rf_num, arrived_conjuncts));
267
268
45.8k
    if (arrived_rf_num == _applied_rf_num) {
269
        // No newly arrived runtime filters, just return;
270
1.88k
        return Status::OK();
271
1.88k
    }
272
273
    // avoid conjunct destroy in used by storage layer
274
43.9k
    _conjuncts.clear();
275
43.9k
    RETURN_IF_ERROR(_local_state->clone_conjunct_ctxs(_conjuncts));
276
43.9k
    _late_arrival_rf_conjuncts.insert(_late_arrival_rf_conjuncts.end(),
277
43.9k
                                      std::make_move_iterator(arrived_conjuncts.begin()),
278
43.9k
                                      std::make_move_iterator(arrived_conjuncts.end()));
279
43.9k
    _applied_rf_num = arrived_rf_num;
280
43.9k
    return Status::OK();
281
43.9k
}
282
283
148k
uint64_t Scanner::_current_condition_cache_digest() const {
284
148k
    DORIS_CHECK(_state != nullptr);
285
148k
    DORIS_CHECK(_local_state != nullptr);
286
148k
    if (_local_state->get_condition_cache_digest() == 0) {
287
27.4k
        return 0;
288
27.4k
    }
289
290
    // ScanLocalState computed its digest after collecting the RFs that were ready during open(). A
291
    // scanner may later clone more RF conjuncts between file splits, so rebuild from its current
292
    // snapshot instead of reusing that stale value. For example, split 0 may use P, while split 1
293
    // starts after an IN RF with payload {7, 9} arrives and must use digest(P AND RF{7, 9}). A
294
    // different payload {8, 10} consequently receives a different key. get_digest() returning zero
295
    // is the correctness fallback for an RF whose complete semantics cannot be represented.
296
121k
    return _build_condition_cache_digest(_state->query_options().condition_cache_digest,
297
121k
                                         _conjuncts);
298
148k
}
299
300
121k
uint64_t Scanner::_build_condition_cache_digest(uint64_t seed, const VExprContextSPtrs& conjuncts) {
301
121k
    for (const auto& conjunct : conjuncts) {
302
64.9k
        seed = conjunct->get_digest(seed);
303
64.9k
        if (seed == 0) {
304
1
            return 0;
305
1
        }
306
64.9k
    }
307
121k
    return seed;
308
121k
}
309
310
#ifdef BE_TEST
311
uint64_t Scanner::TEST_build_condition_cache_digest(uint64_t seed,
312
                                                    const VExprContextSPtrs& conjuncts) {
313
    return _build_condition_cache_digest(seed, conjuncts);
314
}
315
#endif
316
317
1.43M
Status Scanner::close(RuntimeState* state) {
318
1.43M
#ifndef BE_TEST
319
1.43M
    COUNTER_UPDATE(_local_state->_scanner_wait_worker_timer, _scanner_wait_worker_timer);
320
1.43M
#endif
321
1.43M
    return Status::OK();
322
1.43M
}
323
324
1.43M
bool Scanner::_try_close() {
325
1.43M
    bool expected = false;
326
1.43M
    return _is_closed.compare_exchange_strong(expected, true);
327
1.43M
}
328
329
1.42M
void Scanner::_collect_profile_before_close() {
330
1.42M
    COUNTER_UPDATE(_local_state->_scan_cpu_timer, _scan_cpu_timer);
331
1.42M
    COUNTER_UPDATE(_local_state->_rows_read_counter, _num_rows_read);
332
333
    // Update stats for load. See _should_update_load_counters() for why this is gated.
334
1.42M
    if (_should_update_load_counters()) {
335
5.63k
        _state->update_num_rows_load_filtered(_counter.num_rows_filtered);
336
5.63k
        _state->update_num_rows_load_unselected(_counter.num_rows_unselected);
337
5.63k
    }
338
1.42M
}
339
340
1.53M
void Scanner::_update_scan_cpu_timer() {
341
1.53M
    int64_t cpu_time = _cpu_watch.elapsed_time();
342
1.53M
    _scan_cpu_timer += cpu_time;
343
1.54M
    if (_state && _state->get_query_ctx()) {
344
1.54M
        _state->get_query_ctx()->resource_ctx()->cpu_context()->update_cpu_cost_ms(cpu_time);
345
1.54M
    }
346
1.53M
}
347
348
} // namespace doris