Coverage Report

Created: 2026-08-01 17:47

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
876k
        : _state(state),
39
876k
          _local_state(local_state),
40
876k
          _limit(limit),
41
876k
          _profile(profile),
42
876k
          _output_tuple_desc(_local_state->output_tuple_desc()),
43
876k
          _output_row_descriptor(_local_state->_parent->output_row_descriptor()),
44
876k
          _has_prepared(false) {
45
876k
    _total_rf_num = cast_set<int>(_local_state->_helper.runtime_filter_nums());
46
876k
    DorisMetrics::instance()->scanner_cnt->increment(1);
47
876k
}
48
49
877k
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
877k
    _shared_scan_limit = _local_state->shared_scan_limit_ptr();
55
56
877k
    if (!conjuncts.empty()) {
57
6.57k
        _conjuncts.resize(conjuncts.size());
58
14.3k
        for (size_t i = 0; i != conjuncts.size(); ++i) {
59
7.75k
            RETURN_IF_ERROR(conjuncts[i]->clone(state, _conjuncts[i]));
60
7.75k
        }
61
6.57k
    }
62
63
877k
    const auto& projections = _local_state->_projections;
64
877k
    if (!projections.empty()) {
65
813k
        _projections.resize(projections.size());
66
7.83M
        for (size_t i = 0; i != projections.size(); ++i) {
67
7.02M
            RETURN_IF_ERROR(projections[i]->clone(state, _projections[i]));
68
7.02M
        }
69
813k
    }
70
71
877k
    const auto& intermediate_projections = _local_state->_intermediate_projections;
72
877k
    if (!intermediate_projections.empty()) {
73
11.7k
        _intermediate_projections.resize(intermediate_projections.size());
74
29.4k
        for (int i = 0; i < intermediate_projections.size(); i++) {
75
17.6k
            _intermediate_projections[i].resize(intermediate_projections[i].size());
76
105k
            for (int j = 0; j < intermediate_projections[i].size(); j++) {
77
88.1k
                RETURN_IF_ERROR(intermediate_projections[i][j]->clone(
78
88.1k
                        state, _intermediate_projections[i][j]));
79
88.1k
            }
80
17.6k
        }
81
11.7k
    }
82
83
877k
    return Status::OK();
84
877k
}
85
86
927k
Status Scanner::get_block_after_projects(RuntimeState* state, Block* block, bool* eos) {
87
927k
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().vscanner_get_block);
88
927k
    auto& row_descriptor = _local_state->_parent->row_descriptor();
89
927k
    if (_output_row_descriptor) {
90
830k
        _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
91
830k
        const auto min_batch_size = std::max(state->batch_size() / 2, 1);
92
830k
        const auto block_max_bytes = state->preferred_block_size_bytes();
93
1.05M
        while (_padding_block.rows() < min_batch_size && _padding_block.bytes() < block_max_bytes &&
94
1.05M
               !*eos) {
95
1.05M
            RETURN_IF_ERROR(get_block(state, &_origin_block, eos));
96
1.05M
            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
813k
                RETURN_IF_ERROR(_merge_padding_block());
101
813k
                _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
102
813k
                break;
103
813k
            }
104
238k
            if (_origin_block.rows() >= min_batch_size) {
105
16.0k
                break;
106
16.0k
            }
107
108
222k
            if (_origin_block.rows() + _padding_block.rows() <= state->batch_size() &&
109
223k
                _origin_block.bytes() + _padding_block.bytes() <= block_max_bytes) {
110
223k
                RETURN_IF_ERROR(_merge_padding_block());
111
223k
                _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
112
18.4E
            } else {
113
18.4E
                if (_origin_block.rows() < _padding_block.rows()) {
114
0
                    _padding_block.swap(_origin_block);
115
0
                }
116
18.4E
                break;
117
18.4E
            }
118
222k
        }
119
120
830k
        if (_origin_block.empty() && !_padding_block.empty()) {
121
192k
            _padding_block.swap(_origin_block);
122
192k
        }
123
830k
        return _do_projections(&_origin_block, block);
124
830k
    } else {
125
97.2k
        return get_block(state, block, eos);
126
97.2k
    }
127
927k
}
128
129
1.15M
Status Scanner::get_block(RuntimeState* state, Block* block, bool* eof) {
130
    // only empty block should be here
131
1.15M
    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.15M
    if (_shared_scan_limit && _shared_scan_limit->load(std::memory_order_acquire) <= 0) {
137
32
        *eof = true;
138
32
        return Status::OK();
139
32
    }
140
141
    // scanner running time
142
1.15M
    SCOPED_RAW_TIMER(&_per_scanner_timer);
143
1.15M
    int64_t rows_read_threshold = _num_rows_read + config::doris_scanner_row_num;
144
1.15M
    if (!block->mem_reuse()) {
145
8.15M
        for (auto* const slot_desc : _output_tuple_desc->slots()) {
146
8.15M
            block->insert(ColumnWithTypeAndName(slot_desc->get_empty_mutable_column(),
147
8.15M
                                                slot_desc->get_data_type_ptr(),
148
8.15M
                                                slot_desc->col_name()));
149
8.15M
        }
150
1.00M
    }
151
152
1.15M
    {
153
1.15M
        do {
154
            // 1. Get input block from scanner
155
1.15M
            {
156
                // get block time
157
1.15M
                SCOPED_TIMER(_local_state->_scan_timer);
158
1.15M
                RETURN_IF_ERROR(_get_block_impl(state, block, eof));
159
1.15M
                if (*eof) {
160
873k
                    DCHECK(block->rows() == 0);
161
873k
                    break;
162
873k
                }
163
280k
                _num_rows_read += block->rows();
164
280k
                _num_byte_read += block->allocated_bytes();
165
280k
            }
166
167
            // 2. Filter the output block finally.
168
0
            {
169
280k
                SCOPED_TIMER(_local_state->_filter_timer);
170
280k
                RETURN_IF_ERROR(_filter_output_block(block));
171
280k
            }
172
            // record rows return (after filter) for _limit check
173
280k
            _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
280k
            if (_shared_scan_limit && block->rows() > 0) {
179
500
                _shared_scan_limit->fetch_sub(block->rows(), std::memory_order_acq_rel);
180
500
            }
181
281k
        } while (!_should_stop && !state->is_cancelled() && block->rows() == 0 && !(*eof) &&
182
280k
                 _num_rows_read < rows_read_threshold);
183
1.15M
    }
184
185
1.15M
    if (state->is_cancelled()) {
186
        // TODO: Should return the specific ErrorStatus instead of just Cancelled.
187
15
        return Status::Cancelled("cancelled");
188
15
    }
189
1.15M
    *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.15M
    *eof = *eof || (_limit > 0 && _num_rows_return >= _limit);
193
1.15M
    *eof = *eof || (_shared_scan_limit && _shared_scan_limit->load(std::memory_order_acquire) <= 0);
194
195
1.15M
    return Status::OK();
196
1.15M
}
197
198
281k
Status Scanner::_filter_output_block(Block* block) {
199
281k
    auto old_rows = block->rows();
200
281k
    Status st = VExprContext::filter_block(_conjuncts, block, block->columns());
201
281k
    _counter.num_rows_unselected += old_rows - block->rows();
202
281k
    return st;
203
281k
}
204
205
831k
Status Scanner::_do_projections(Block* origin_block, Block* output_block) {
206
831k
    SCOPED_RAW_TIMER(&_per_scanner_timer);
207
831k
    SCOPED_RAW_TIMER(&_projection_timer);
208
209
831k
    const size_t rows = origin_block->rows();
210
831k
    if (rows == 0) {
211
622k
        return Status::OK();
212
622k
    }
213
214
209k
    {
215
209k
        Block input_block = *origin_block;
216
217
209k
        std::vector<int> result_column_ids;
218
209k
        for (auto& projections : _intermediate_projections) {
219
22.0k
            result_column_ids.resize(projections.size());
220
136k
            for (int i = 0; i < projections.size(); i++) {
221
114k
                RETURN_IF_ERROR(projections[i]->execute(&input_block, &result_column_ids[i]));
222
114k
            }
223
22.0k
            input_block.shuffle_columns(result_column_ids);
224
22.0k
        }
225
226
209k
        DCHECK_EQ(rows, input_block.rows());
227
209k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
228
209k
                output_block, *_output_row_descriptor);
229
209k
        auto& mutable_columns = scoped_mutable_block.mutable_columns();
230
209k
        DCHECK_EQ(mutable_columns.size(), _projections.size());
231
209k
        Columns shared_columns(mutable_columns.size());
232
233
765k
        for (int i = 0; i < mutable_columns.size(); ++i) {
234
556k
            ColumnPtr column_ptr;
235
556k
            RETURN_IF_ERROR(_projections[i]->execute(&input_block, column_ptr));
236
555k
            column_ptr = column_ptr->convert_to_full_column_if_const();
237
555k
            if (mutable_columns[i]->is_nullable() != column_ptr->is_nullable()) {
238
0
                throw Exception(ErrorCode::INTERNAL_ERROR, "Nullable mismatch");
239
0
            }
240
555k
            if (column_ptr->is_exclusive()) {
241
119k
                mutable_columns[i] = IColumn::mutate(std::move(column_ptr));
242
436k
            } else {
243
436k
                shared_columns[i] = std::move(column_ptr);
244
436k
            }
245
555k
        }
246
247
208k
        scoped_mutable_block.restore();
248
763k
        for (int i = 0; i < shared_columns.size(); ++i) {
249
555k
            if (shared_columns[i]) {
250
436k
                output_block->replace_by_position(i, std::move(shared_columns[i]));
251
436k
            }
252
555k
        }
253
208k
    }
254
255
0
    origin_block->clear_column_data(
256
208k
            _local_state->_parent->row_descriptor().num_materialized_slots());
257
208k
    DCHECK_EQ(output_block->rows(), rows);
258
259
208k
    return Status::OK();
260
209k
}
261
262
928k
Status Scanner::try_append_late_arrival_runtime_filter() {
263
928k
    if (_applied_rf_num == _total_rf_num) {
264
895k
        return Status::OK();
265
895k
    }
266
928k
    DCHECK(_applied_rf_num < _total_rf_num);
267
32.6k
    int arrived_rf_num = 0;
268
32.6k
    RETURN_IF_ERROR(_local_state->update_late_arrival_runtime_filter(_state, arrived_rf_num));
269
270
32.6k
    if (arrived_rf_num == _applied_rf_num) {
271
        // No newly arrived runtime filters, just return;
272
543
        return Status::OK();
273
543
    }
274
275
    // avoid conjunct destroy in used by storage layer
276
32.1k
    _conjuncts.clear();
277
32.1k
    RETURN_IF_ERROR(_local_state->clone_conjunct_ctxs(_conjuncts));
278
32.1k
    _applied_rf_num = arrived_rf_num;
279
32.1k
    return Status::OK();
280
32.1k
}
281
282
5.92k
uint64_t Scanner::_current_condition_cache_digest() const {
283
5.92k
    DORIS_CHECK(_state != nullptr);
284
5.92k
    DORIS_CHECK(_local_state != nullptr);
285
5.92k
    if (_local_state->get_condition_cache_digest() == 0) {
286
5.05k
        return 0;
287
5.05k
    }
288
289
    // ScanLocalState computed its digest after collecting the RFs that were ready during open(). A
290
    // scanner may later clone more RF conjuncts between file splits, so rebuild from its current
291
    // snapshot instead of reusing that stale value. For example, split 0 may use P, while split 1
292
    // starts after an IN RF with payload {7, 9} arrives and must use digest(P AND RF{7, 9}). A
293
    // different payload {8, 10} consequently receives a different key. get_digest() returning zero
294
    // is the correctness fallback for an RF whose complete semantics cannot be represented.
295
877
    return _build_condition_cache_digest(_state->query_options().condition_cache_digest,
296
877
                                         _conjuncts);
297
5.92k
}
298
299
890
uint64_t Scanner::_build_condition_cache_digest(uint64_t seed, const VExprContextSPtrs& conjuncts) {
300
890
    for (const auto& conjunct : conjuncts) {
301
36
        seed = conjunct->get_digest(seed);
302
36
        if (seed == 0) {
303
1
            return 0;
304
1
        }
305
36
    }
306
889
    return seed;
307
890
}
308
309
#ifdef BE_TEST
310
uint64_t Scanner::TEST_build_condition_cache_digest(uint64_t seed,
311
                                                    const VExprContextSPtrs& conjuncts) {
312
    return _build_condition_cache_digest(seed, conjuncts);
313
}
314
#endif
315
316
880k
Status Scanner::close(RuntimeState* state) {
317
880k
#ifndef BE_TEST
318
880k
    COUNTER_UPDATE(_local_state->_scanner_wait_worker_timer, _scanner_wait_worker_timer);
319
880k
#endif
320
880k
    return Status::OK();
321
880k
}
322
323
880k
bool Scanner::_try_close() {
324
880k
    bool expected = false;
325
880k
    return _is_closed.compare_exchange_strong(expected, true);
326
880k
}
327
328
873k
void Scanner::_collect_profile_before_close() {
329
873k
    COUNTER_UPDATE(_local_state->_scan_cpu_timer, _scan_cpu_timer);
330
873k
    COUNTER_UPDATE(_local_state->_rows_read_counter, _num_rows_read);
331
332
    // Update stats for load. See _should_update_load_counters() for why this is gated.
333
873k
    if (_should_update_load_counters()) {
334
2.64k
        _state->update_num_rows_load_filtered(_counter.num_rows_filtered);
335
2.64k
        _state->update_num_rows_load_unselected(_counter.num_rows_unselected);
336
2.64k
    }
337
873k
}
338
339
927k
void Scanner::_update_scan_cpu_timer() {
340
927k
    int64_t cpu_time = _cpu_watch.elapsed_time();
341
927k
    _scan_cpu_timer += cpu_time;
342
929k
    if (_state && _state->get_query_ctx()) {
343
929k
        _state->get_query_ctx()->resource_ctx()->cpu_context()->update_cpu_cost_ms(cpu_time);
344
929k
    }
345
927k
}
346
347
} // namespace doris