Coverage Report

Created: 2026-08-06 17:23

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.41M
        : _state(state),
39
1.41M
          _local_state(local_state),
40
1.41M
          _limit(limit),
41
1.41M
          _profile(profile),
42
1.41M
          _output_tuple_desc(_local_state->output_tuple_desc()),
43
1.41M
          _output_row_descriptor(_local_state->_parent->output_row_descriptor()),
44
1.41M
          _has_prepared(false) {
45
1.41M
    _total_rf_num = cast_set<int>(_local_state->_helper.runtime_filter_nums());
46
1.41M
    DorisMetrics::instance()->scanner_cnt->increment(1);
47
1.41M
}
48
49
1.41M
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.41M
    _shared_scan_limit = _local_state->shared_scan_limit_ptr();
55
56
1.41M
    if (!conjuncts.empty()) {
57
47.3k
        _conjuncts.resize(conjuncts.size());
58
110k
        for (size_t i = 0; i != conjuncts.size(); ++i) {
59
62.9k
            RETURN_IF_ERROR(conjuncts[i]->clone(state, _conjuncts[i]));
60
62.9k
        }
61
47.3k
    }
62
63
1.41M
    const auto& projections = _local_state->_projections;
64
1.41M
    if (!projections.empty()) {
65
1.31M
        _projections.resize(projections.size());
66
14.3M
        for (size_t i = 0; i != projections.size(); ++i) {
67
13.0M
            RETURN_IF_ERROR(projections[i]->clone(state, _projections[i]));
68
13.0M
        }
69
1.31M
    }
70
71
1.41M
    const auto& intermediate_projections = _local_state->_intermediate_projections;
72
1.41M
    if (!intermediate_projections.empty()) {
73
14.8k
        _intermediate_projections.resize(intermediate_projections.size());
74
47.9k
        for (int i = 0; i < intermediate_projections.size(); i++) {
75
33.1k
            _intermediate_projections[i].resize(intermediate_projections[i].size());
76
197k
            for (int j = 0; j < intermediate_projections[i].size(); j++) {
77
164k
                RETURN_IF_ERROR(intermediate_projections[i][j]->clone(
78
164k
                        state, _intermediate_projections[i][j]));
79
164k
            }
80
33.1k
        }
81
14.8k
    }
82
83
1.41M
    return Status::OK();
84
1.41M
}
85
86
1.52M
Status Scanner::get_block_after_projects(RuntimeState* state, Block* block, bool* eos) {
87
1.52M
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().vscanner_get_block);
88
1.52M
    auto& row_descriptor = _local_state->_parent->row_descriptor();
89
1.52M
    if (_output_row_descriptor) {
90
1.34M
        _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
91
1.34M
        if (!_can_merge_padding_blocks(_padding_block, _origin_block)) {
92
497
            DORIS_CHECK(_padding_block.empty())
93
2
                    << "padding policy must remain stable for one scanner";
94
            // Some physical columns carry file-local state that an upper projection must consume
95
            // before the next split is read. Padding those blocks first would make correctness
96
            // depend on whether two file tails happen to share one output batch.
97
497
            RETURN_IF_ERROR(get_block(state, &_origin_block, eos));
98
497
            return _do_projections(&_origin_block, block);
99
497
        }
100
1.34M
        const auto min_batch_size = std::max(state->batch_size() / 2, 1);
101
1.34M
        const auto block_max_bytes = state->preferred_block_size_bytes();
102
1.71M
        while (_padding_block.rows() < min_batch_size && _padding_block.bytes() < block_max_bytes &&
103
1.71M
               !*eos) {
104
1.70M
            RETURN_IF_ERROR(get_block(state, &_origin_block, eos));
105
1.70M
            if (*eos) {
106
                // For the final block, merge any padding directly and return eos in this call.
107
                // The merged tail can be larger than the target batch, but each source block is
108
                // already bounded by the lower scanner.
109
1.30M
                RETURN_IF_ERROR(_merge_padding_block());
110
1.30M
                _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
111
1.30M
                break;
112
1.30M
            }
113
402k
            if (_origin_block.rows() >= min_batch_size) {
114
37.0k
                break;
115
37.0k
            }
116
117
365k
            if (_origin_block.rows() + _padding_block.rows() <= state->batch_size() &&
118
366k
                _origin_block.bytes() + _padding_block.bytes() <= block_max_bytes) {
119
366k
                RETURN_IF_ERROR(_merge_padding_block());
120
366k
                _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
121
18.4E
            } else {
122
18.4E
                if (_origin_block.rows() < _padding_block.rows()) {
123
0
                    _padding_block.swap(_origin_block);
124
0
                }
125
18.4E
                break;
126
18.4E
            }
127
365k
        }
128
129
1.34M
        if (_origin_block.empty() && !_padding_block.empty()) {
130
256k
            _padding_block.swap(_origin_block);
131
256k
        }
132
1.34M
        return _do_projections(&_origin_block, block);
133
1.34M
    } else {
134
180k
        return get_block(state, block, eos);
135
180k
    }
136
1.52M
}
137
138
1.88M
Status Scanner::get_block(RuntimeState* state, Block* block, bool* eof) {
139
    // only empty block should be here
140
1.88M
    DCHECK(block->rows() == 0);
141
142
    // Stop early if other scanners have already collected enough rows
143
    // for the SQL LIMIT. Skipped when _shared_scan_limit is null (topn
144
    // path or no LIMIT).
145
1.88M
    if (_shared_scan_limit && _shared_scan_limit->load(std::memory_order_acquire) <= 0) {
146
38
        *eof = true;
147
38
        return Status::OK();
148
38
    }
149
150
    // scanner running time
151
1.88M
    SCOPED_RAW_TIMER(&_per_scanner_timer);
152
1.88M
    int64_t rows_read_threshold = _num_rows_read + config::doris_scanner_row_num;
153
1.88M
    if (!block->mem_reuse()) {
154
14.6M
        for (auto* const slot_desc : _output_tuple_desc->slots()) {
155
14.6M
            block->insert(ColumnWithTypeAndName(slot_desc->get_empty_mutable_column(),
156
14.6M
                                                slot_desc->get_data_type_ptr(),
157
14.6M
                                                slot_desc->col_name()));
158
14.6M
        }
159
1.56M
    }
160
161
1.88M
    {
162
1.90M
        do {
163
            // 1. Get input block from scanner
164
1.90M
            {
165
                // get block time
166
1.90M
                SCOPED_TIMER(_local_state->_scan_timer);
167
1.90M
                RETURN_IF_ERROR(_get_block_impl(state, block, eof));
168
1.90M
                if (*eof) {
169
1.41M
                    DCHECK(block->rows() == 0);
170
1.41M
                    break;
171
1.41M
                }
172
489k
                _num_rows_read += block->rows();
173
489k
                _num_byte_read += block->allocated_bytes();
174
489k
            }
175
176
            // 2. Filter the output block finally.
177
0
            {
178
489k
                SCOPED_TIMER(_local_state->_filter_timer);
179
489k
                RETURN_IF_ERROR(_filter_output_block(block));
180
489k
            }
181
            // record rows return (after filter) for _limit check
182
489k
            _num_rows_return += block->rows();
183
            // Publish progress to the shared counter so peer scanners can
184
            // observe it. The counter may go negative when several scanners
185
            // subtract concurrently; that is harmless because the operator's
186
            // reached_limit() makes the final cut.
187
489k
            if (_shared_scan_limit && block->rows() > 0) {
188
3.18k
                _shared_scan_limit->fetch_sub(block->rows(), std::memory_order_acq_rel);
189
3.18k
            }
190
493k
        } while (!_should_stop && !state->is_cancelled() && block->rows() == 0 && !(*eof) &&
191
489k
                 _num_rows_read < rows_read_threshold);
192
1.88M
    }
193
194
1.88M
    if (state->is_cancelled()) {
195
        // TODO: Should return the specific ErrorStatus instead of just Cancelled.
196
15
        return Status::Cancelled("cancelled");
197
15
    }
198
1.88M
    *eof = *eof || _should_stop;
199
    // set eof to true if per scanner limit is reached
200
    // currently for query: ORDER BY key LIMIT n
201
1.88M
    *eof = *eof || (_limit > 0 && _num_rows_return >= _limit);
202
1.88M
    *eof = *eof || (_shared_scan_limit && _shared_scan_limit->load(std::memory_order_acquire) <= 0);
203
204
1.88M
    return Status::OK();
205
1.88M
}
206
207
493k
Status Scanner::_filter_output_block(Block* block) {
208
493k
    auto old_rows = block->rows();
209
493k
    Status st = VExprContext::filter_block(_conjuncts, block, block->columns());
210
493k
    _counter.num_rows_unselected += old_rows - block->rows();
211
493k
    return st;
212
493k
}
213
214
1.34M
Status Scanner::_do_projections(Block* origin_block, Block* output_block) {
215
1.34M
    SCOPED_RAW_TIMER(&_per_scanner_timer);
216
1.34M
    SCOPED_RAW_TIMER(&_projection_timer);
217
218
1.34M
    const size_t rows = origin_block->rows();
219
1.34M
    if (rows == 0) {
220
1.05M
        return Status::OK();
221
1.05M
    }
222
223
292k
    {
224
292k
        Block input_block = *origin_block;
225
226
292k
        std::vector<int> result_column_ids;
227
292k
        for (auto& projections : _intermediate_projections) {
228
43.8k
            result_column_ids.resize(projections.size());
229
306k
            for (int i = 0; i < projections.size(); i++) {
230
262k
                RETURN_IF_ERROR(projections[i]->execute(&input_block, &result_column_ids[i]));
231
262k
            }
232
43.8k
            input_block.shuffle_columns(result_column_ids);
233
43.8k
        }
234
235
292k
        DCHECK_EQ(rows, input_block.rows());
236
292k
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
237
292k
                output_block, *_output_row_descriptor);
238
292k
        auto& mutable_columns = scoped_mutable_block.mutable_columns();
239
292k
        DCHECK_EQ(mutable_columns.size(), _projections.size());
240
292k
        Columns shared_columns(mutable_columns.size());
241
242
1.06M
        for (int i = 0; i < mutable_columns.size(); ++i) {
243
771k
            ColumnPtr column_ptr;
244
771k
            RETURN_IF_ERROR(_projections[i]->execute(&input_block, column_ptr));
245
770k
            column_ptr = column_ptr->convert_to_full_column_if_const();
246
770k
            if (mutable_columns[i]->is_nullable() != column_ptr->is_nullable()) {
247
0
                throw Exception(ErrorCode::INTERNAL_ERROR, "Nullable mismatch");
248
0
            }
249
770k
            if (column_ptr->is_exclusive()) {
250
160k
                mutable_columns[i] = IColumn::mutate(std::move(column_ptr));
251
609k
            } else {
252
609k
                shared_columns[i] = std::move(column_ptr);
253
609k
            }
254
770k
        }
255
256
291k
        scoped_mutable_block.restore();
257
1.06M
        for (int i = 0; i < shared_columns.size(); ++i) {
258
769k
            if (shared_columns[i]) {
259
609k
                output_block->replace_by_position(i, std::move(shared_columns[i]));
260
609k
            }
261
769k
        }
262
291k
    }
263
264
0
    origin_block->clear_column_data(
265
291k
            _local_state->_parent->row_descriptor().num_materialized_slots());
266
291k
    DCHECK_EQ(output_block->rows(), rows);
267
268
291k
    return Status::OK();
269
292k
}
270
271
1.52M
Status Scanner::try_append_late_arrival_runtime_filter() {
272
1.52M
    if (_applied_rf_num == _total_rf_num) {
273
1.48M
        return Status::OK();
274
1.48M
    }
275
1.52M
    DCHECK(_applied_rf_num < _total_rf_num);
276
41.7k
    int arrived_rf_num = 0;
277
41.7k
    RETURN_IF_ERROR(_local_state->update_late_arrival_runtime_filter(_state, arrived_rf_num));
278
279
41.7k
    if (arrived_rf_num == _applied_rf_num) {
280
        // No newly arrived runtime filters, just return;
281
1.23k
        return Status::OK();
282
1.23k
    }
283
284
    // avoid conjunct destroy in used by storage layer
285
40.4k
    _conjuncts.clear();
286
40.4k
    RETURN_IF_ERROR(_local_state->clone_conjunct_ctxs(_conjuncts));
287
40.4k
    _applied_rf_num = arrived_rf_num;
288
40.4k
    return Status::OK();
289
40.4k
}
290
291
142k
uint64_t Scanner::_current_condition_cache_digest() const {
292
142k
    DORIS_CHECK(_state != nullptr);
293
142k
    DORIS_CHECK(_local_state != nullptr);
294
142k
    if (_local_state->get_condition_cache_digest() == 0) {
295
25.5k
        return 0;
296
25.5k
    }
297
298
    // ScanLocalState computed its digest after collecting the RFs that were ready during open(). A
299
    // scanner may later clone more RF conjuncts between file splits, so rebuild from its current
300
    // snapshot instead of reusing that stale value. For example, split 0 may use P, while split 1
301
    // starts after an IN RF with payload {7, 9} arrives and must use digest(P AND RF{7, 9}). A
302
    // different payload {8, 10} consequently receives a different key. get_digest() returning zero
303
    // is the correctness fallback for an RF whose complete semantics cannot be represented.
304
117k
    return _build_condition_cache_digest(_state->query_options().condition_cache_digest,
305
117k
                                         _conjuncts);
306
142k
}
307
308
117k
uint64_t Scanner::_build_condition_cache_digest(uint64_t seed, const VExprContextSPtrs& conjuncts) {
309
117k
    for (const auto& conjunct : conjuncts) {
310
62.4k
        seed = conjunct->get_digest(seed);
311
62.4k
        if (seed == 0) {
312
1
            return 0;
313
1
        }
314
62.4k
    }
315
117k
    return seed;
316
117k
}
317
318
#ifdef BE_TEST
319
uint64_t Scanner::TEST_build_condition_cache_digest(uint64_t seed,
320
                                                    const VExprContextSPtrs& conjuncts) {
321
    return _build_condition_cache_digest(seed, conjuncts);
322
}
323
#endif
324
325
1.42M
Status Scanner::close(RuntimeState* state) {
326
1.42M
#ifndef BE_TEST
327
1.42M
    COUNTER_UPDATE(_local_state->_scanner_wait_worker_timer, _scanner_wait_worker_timer);
328
1.42M
#endif
329
1.42M
    return Status::OK();
330
1.42M
}
331
332
1.42M
bool Scanner::_try_close() {
333
1.42M
    bool expected = false;
334
1.42M
    return _is_closed.compare_exchange_strong(expected, true);
335
1.42M
}
336
337
1.40M
void Scanner::_collect_profile_before_close() {
338
1.40M
    COUNTER_UPDATE(_local_state->_scan_cpu_timer, _scan_cpu_timer);
339
1.40M
    COUNTER_UPDATE(_local_state->_rows_read_counter, _num_rows_read);
340
341
    // Update stats for load. See _should_update_load_counters() for why this is gated.
342
1.40M
    if (_should_update_load_counters()) {
343
5.63k
        _state->update_num_rows_load_filtered(_counter.num_rows_filtered);
344
5.63k
        _state->update_num_rows_load_unselected(_counter.num_rows_unselected);
345
5.63k
    }
346
1.40M
}
347
348
1.52M
void Scanner::_update_scan_cpu_timer() {
349
1.52M
    int64_t cpu_time = _cpu_watch.elapsed_time();
350
1.52M
    _scan_cpu_timer += cpu_time;
351
1.52M
    if (_state && _state->get_query_ctx()) {
352
1.52M
        _state->get_query_ctx()->resource_ctx()->cpu_context()->update_cpu_cost_ms(cpu_time);
353
1.52M
    }
354
1.52M
}
355
356
} // namespace doris