Coverage Report

Created: 2026-09-30 00:38

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