Coverage Report

Created: 2026-08-18 03:43

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
20
        : _state(state),
39
20
          _local_state(local_state),
40
20
          _limit(limit),
41
20
          _profile(profile),
42
20
          _output_tuple_desc(_local_state->output_tuple_desc()),
43
20
          _output_row_descriptor(_local_state->_parent->output_row_descriptor()),
44
20
          _has_prepared(false) {
45
20
    _total_rf_num = cast_set<int>(_local_state->_helper.runtime_filter_nums());
46
20
    DorisMetrics::instance()->scanner_cnt->increment(1);
47
20
}
48
49
9
Status Scanner::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
50
9
    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
9
    const auto& projections = _local_state->_projections;
58
9
    if (!projections.empty()) {
59
3
        _projections.resize(projections.size());
60
6
        for (size_t i = 0; i != projections.size(); ++i) {
61
3
            RETURN_IF_ERROR(projections[i]->clone(state, _projections[i]));
62
3
        }
63
3
    }
64
65
9
    const auto& intermediate_projections = _local_state->_intermediate_projections;
66
9
    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
9
    return Status::OK();
78
9
}
79
80
6
Status Scanner::get_block_after_projects(RuntimeState* state, Block* block, bool* eos) {
81
6
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().vscanner_get_block);
82
6
    auto& row_descriptor = _local_state->_parent->row_descriptor();
83
6
    if (_output_row_descriptor) {
84
6
        _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
85
6
        if (!_can_merge_padding_blocks(_padding_block, _origin_block)) {
86
3
            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
3
            RETURN_IF_ERROR(get_block(state, &_origin_block, eos));
92
3
            return _do_projections(&_origin_block, block);
93
3
        }
94
3
        const auto min_batch_size = std::max(state->batch_size() / 2, 1);
95
3
        const auto block_max_bytes = state->preferred_block_size_bytes();
96
4
        while (_padding_block.rows() < min_batch_size && _padding_block.bytes() < block_max_bytes &&
97
4
               !*eos) {
98
4
            RETURN_IF_ERROR(get_block(state, &_origin_block, eos));
99
4
            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
1
                RETURN_IF_ERROR(_merge_padding_block());
104
1
                _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
105
1
                break;
106
1
            }
107
3
            if (_origin_block.rows() >= min_batch_size) {
108
2
                break;
109
2
            }
110
111
1
            if (_origin_block.rows() + _padding_block.rows() <= state->batch_size() &&
112
1
                _origin_block.bytes() + _padding_block.bytes() <= block_max_bytes) {
113
1
                RETURN_IF_ERROR(_merge_padding_block());
114
1
                _origin_block.clear_column_data(row_descriptor.num_materialized_slots());
115
1
            } 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
1
        }
122
123
3
        if (_origin_block.empty() && !_padding_block.empty()) {
124
1
            _padding_block.swap(_origin_block);
125
1
        }
126
3
        return _do_projections(&_origin_block, block);
127
3
    } else {
128
0
        return get_block(state, block, eos);
129
0
    }
130
6
}
131
132
13
Status Scanner::get_block(RuntimeState* state, Block* block, bool* eof) {
133
    // only empty block should be here
134
13
    DCHECK(block->rows() == 0);
135
    // scanner running time
136
13
    SCOPED_RAW_TIMER(&_per_scanner_timer);
137
13
    int64_t rows_read_threshold = _num_rows_read + config::doris_scanner_row_num;
138
13
    if (!block->mem_reuse()) {
139
19
        for (auto* const slot_desc : _output_tuple_desc->slots()) {
140
19
            block->insert(ColumnWithTypeAndName(slot_desc->get_empty_mutable_column(),
141
19
                                                slot_desc->get_data_type_ptr(),
142
19
                                                slot_desc->col_name()));
143
19
        }
144
9
    }
145
146
13
    {
147
15
        do {
148
            // 1. Get input block from scanner
149
15
            {
150
                // get block time
151
15
                SCOPED_TIMER(_local_state->_scan_timer);
152
15
                RETURN_IF_ERROR(_get_block_impl(state, block, eof));
153
13
                if (*eof) {
154
3
                    DCHECK(block->rows() == 0);
155
3
                    break;
156
3
                }
157
10
                _num_rows_read += block->rows();
158
10
                _num_byte_read += block->allocated_bytes();
159
10
            }
160
161
            // 2. Filter the output block finally.
162
0
            {
163
10
                SCOPED_TIMER(_local_state->_filter_timer);
164
10
                RETURN_IF_ERROR(_filter_output_block(block));
165
10
            }
166
            // record rows return (after filter) for _limit check
167
10
            _num_rows_return += block->rows();
168
10
        } while (!_should_stop && !state->is_cancelled() && block->rows() == 0 && !(*eof) &&
169
10
                 _num_rows_read < rows_read_threshold);
170
13
    }
171
172
11
    if (state->is_cancelled()) {
173
        // TODO: Should return the specific ErrorStatus instead of just Cancelled.
174
0
        return Status::Cancelled("cancelled");
175
0
    }
176
11
    *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
11
    *eof = *eof || (_limit > 0 && _num_rows_return >= _limit);
180
181
11
    return Status::OK();
182
11
}
183
184
10
Status Scanner::_filter_output_block(Block* block) {
185
10
    auto old_rows = block->rows();
186
10
    Status st = VExprContext::filter_block(_conjuncts, block, block->columns());
187
10
    _counter.num_rows_unselected += old_rows - block->rows();
188
10
    return st;
189
10
}
190
191
6
Status Scanner::_do_projections(Block* origin_block, Block* output_block) {
192
6
    SCOPED_RAW_TIMER(&_per_scanner_timer);
193
6
    SCOPED_RAW_TIMER(&_projection_timer);
194
195
6
    const size_t rows = origin_block->rows();
196
6
    if (rows == 0) {
197
1
        return Status::OK();
198
1
    }
199
200
5
    {
201
5
        Block input_block = *origin_block;
202
203
5
        std::vector<int> result_column_ids;
204
5
        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
5
        DCHECK_EQ(rows, input_block.rows());
213
5
        auto scoped_mutable_block = VectorizedUtils::build_scoped_mutable_mem_reuse_block(
214
5
                output_block, *_output_row_descriptor);
215
5
        auto& mutable_columns = scoped_mutable_block.mutable_columns();
216
5
        DCHECK_EQ(mutable_columns.size(), _projections.size());
217
5
        Columns shared_columns(mutable_columns.size());
218
219
10
        for (int i = 0; i < mutable_columns.size(); ++i) {
220
5
            ColumnPtr column_ptr;
221
5
            RETURN_IF_ERROR(_projections[i]->execute(&input_block, column_ptr));
222
5
            column_ptr = column_ptr->convert_to_full_column_if_const();
223
5
            if (mutable_columns[i]->is_nullable() != column_ptr->is_nullable()) {
224
0
                throw Exception(ErrorCode::INTERNAL_ERROR, "Nullable mismatch");
225
0
            }
226
5
            if (column_ptr->is_exclusive()) {
227
0
                mutable_columns[i] = IColumn::mutate(std::move(column_ptr));
228
5
            } else {
229
5
                shared_columns[i] = std::move(column_ptr);
230
5
            }
231
5
        }
232
233
5
        scoped_mutable_block.restore();
234
10
        for (int i = 0; i < shared_columns.size(); ++i) {
235
5
            if (shared_columns[i]) {
236
5
                output_block->replace_by_position(i, std::move(shared_columns[i]));
237
5
            }
238
5
        }
239
5
    }
240
241
0
    origin_block->clear_column_data(
242
5
            _local_state->_parent->row_descriptor().num_materialized_slots());
243
5
    DCHECK_EQ(output_block->rows(), rows);
244
245
5
    return Status::OK();
246
5
}
247
248
2
Status Scanner::try_append_late_arrival_runtime_filter() {
249
2
    if (_applied_rf_num == _total_rf_num) {
250
1
        return Status::OK();
251
1
    }
252
2
    DCHECK(_applied_rf_num < _total_rf_num);
253
1
    int arrived_rf_num = 0;
254
1
    RETURN_IF_ERROR(_local_state->update_late_arrival_runtime_filter(_state, arrived_rf_num));
255
256
1
    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
1
    _conjuncts.clear();
263
1
    RETURN_IF_ERROR(_local_state->clone_conjunct_ctxs(_conjuncts));
264
1
    _applied_rf_num = arrived_rf_num;
265
1
    return Status::OK();
266
1
}
267
268
2
uint64_t Scanner::_current_condition_cache_digest() const {
269
2
    DORIS_CHECK(_state != nullptr);
270
2
    DORIS_CHECK(_local_state != nullptr);
271
2
    if (_local_state->get_condition_cache_digest() == 0) {
272
2
        return 0;
273
2
    }
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
2
}
284
285
13
uint64_t Scanner::_build_condition_cache_digest(uint64_t seed, const VExprContextSPtrs& conjuncts) {
286
13
    for (const auto& conjunct : conjuncts) {
287
13
        seed = conjunct->get_digest(seed);
288
13
        if (seed == 0) {
289
1
            return 0;
290
1
        }
291
13
    }
292
12
    return seed;
293
13
}
294
295
#ifdef BE_TEST
296
uint64_t Scanner::TEST_build_condition_cache_digest(uint64_t seed,
297
13
                                                    const VExprContextSPtrs& conjuncts) {
298
13
    return _build_condition_cache_digest(seed, conjuncts);
299
13
}
300
#endif
301
302
17
Status Scanner::close(RuntimeState* state) {
303
17
    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
17
    _is_closed = true;
310
17
    return Status::OK();
311
17
}
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