Coverage Report

Created: 2026-06-11 19:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/scan/olap_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/olap_scanner.h"
19
20
#include <gen_cpp/Descriptors_types.h>
21
#include <gen_cpp/PlanNodes_types.h>
22
#include <gen_cpp/Types_types.h>
23
#include <glog/logging.h>
24
#include <stdlib.h>
25
#include <thrift/protocol/TDebugProtocol.h>
26
27
#include <algorithm>
28
#include <atomic>
29
#include <iterator>
30
#include <ostream>
31
#include <set>
32
33
#include "cloud/cloud_storage_engine.h"
34
#include "cloud/cloud_tablet_hotspot.h"
35
#include "cloud/config.h"
36
#include "common/config.h"
37
#include "common/consts.h"
38
#include "common/logging.h"
39
#include "common/metrics/doris_metrics.h"
40
#include "core/block/block.h"
41
#include "exec/common/variant_util.h"
42
#include "exec/operator/olap_scan_operator.h"
43
#include "exec/scan/scan_node.h"
44
#include "exprs/function_filter.h"
45
#include "exprs/vexpr.h"
46
#include "exprs/vexpr_context.h"
47
#include "io/cache/block_file_cache_profile.h"
48
#include "io/io_common.h"
49
#include "runtime/descriptors.h"
50
#include "runtime/exec_env.h"
51
#include "runtime/runtime_profile.h"
52
#include "runtime/runtime_state.h"
53
#include "service/backend_options.h"
54
#include "storage/id_manager.h"
55
#include "storage/index/inverted/inverted_index_profile.h"
56
#include "storage/iterator/block_reader.h"
57
#include "storage/olap_common.h"
58
#include "storage/olap_tuple.h"
59
#include "storage/olap_utils.h"
60
#include "storage/storage_engine.h"
61
#include "storage/tablet/tablet_schema.h"
62
#ifndef NDEBUG
63
#include "util/debug_points.h"
64
#endif
65
#include "util/json/path_in_data.h"
66
67
namespace doris {
68
#include "common/compile_check_avoid_begin.h"
69
70
using ReadSource = TabletReadSource;
71
72
OlapScanner::OlapScanner(ScanLocalStateBase* parent, OlapScanner::Params&& params)
73
1.54k
        : Scanner(params.state, parent, params.limit, params.profile),
74
1.54k
          _key_ranges(std::move(params.key_ranges)),
75
1.54k
          _tablet_reader_params({.tablet = std::move(params.tablet),
76
1.54k
                                 .tablet_schema {},
77
1.54k
                                 .reader_type = params.read_row_binlog ? ReaderType::READER_BINLOG
78
1.54k
                                                                       : ReaderType::READER_QUERY,
79
1.54k
                                 .aggregation = params.aggregation,
80
1.54k
                                 .version = {0, params.version},
81
1.54k
                                 .start_key {},
82
1.54k
                                 .end_key {},
83
1.54k
                                 .predicates {},
84
1.54k
                                 .function_filters {},
85
1.54k
                                 .delete_predicates {},
86
1.54k
                                 .target_cast_type_for_variants {},
87
1.54k
                                 .all_access_paths {},
88
1.54k
                                 .predicate_access_paths {},
89
1.54k
                                 .rs_splits {},
90
1.54k
                                 .return_columns {},
91
1.54k
                                 .output_columns {},
92
1.54k
                                 .filled_columns {},
93
1.54k
                                 .common_expr_ctxs_push_down {},
94
1.54k
                                 .topn_filter_source_node_ids {},
95
1.54k
                                 .key_group_cluster_key_idxes {},
96
1.54k
                                 .virtual_column_exprs {},
97
1.54k
                                 .score_runtime {},
98
1.54k
                                 .collection_statistics {},
99
1.54k
                                 .ann_topn_runtime {},
100
1.54k
                                 .condition_cache_digest = parent->get_condition_cache_digest()}) {
101
1.54k
    _tablet_reader_params.set_read_source(std::move(params.read_source),
102
1.54k
                                          _state->skip_delete_bitmap());
103
1.54k
    _has_prepared = false;
104
1.54k
    _vector_search_params = params.state->get_vector_search_params();
105
1.54k
}
106
107
static std::string read_columns_to_string(TabletSchemaSPtr tablet_schema,
108
0
                                          const std::vector<uint32_t>& read_columns) {
109
    // avoid too long for one line,
110
    // it is hard to display in `show profile` stmt if one line is too long.
111
0
    const int col_per_line = 10;
112
0
    int i = 0;
113
0
    std::string read_columns_string;
114
0
    read_columns_string += "[";
115
0
    for (auto it = read_columns.cbegin(); it != read_columns.cend(); it++) {
116
0
        if (it != read_columns.cbegin()) {
117
0
            read_columns_string += ", ";
118
0
        }
119
0
        read_columns_string += tablet_schema->columns().at(*it)->name();
120
0
        if (i >= col_per_line) {
121
0
            read_columns_string += "\n";
122
0
            i = 0;
123
0
        } else {
124
0
            ++i;
125
0
        }
126
0
    }
127
0
    read_columns_string += "]";
128
0
    return read_columns_string;
129
0
}
130
131
3.06k
static bool has_file_cache_statistics(const io::FileCacheStatistics& stats) {
132
3.06k
    return stats.num_local_io_total != 0 || stats.num_remote_io_total != 0 ||
133
3.06k
           stats.num_peer_io_total != 0 || stats.local_io_timer != 0 ||
134
3.06k
           stats.bytes_read_from_local != 0 || stats.bytes_read_from_remote != 0 ||
135
3.06k
           stats.bytes_read_from_peer != 0 || stats.remote_io_timer != 0 ||
136
3.06k
           stats.peer_io_timer != 0 || stats.remote_wait_timer != 0 ||
137
3.06k
           stats.write_cache_io_timer != 0 || stats.bytes_write_into_cache != 0 ||
138
3.06k
           stats.num_skip_cache_io_total != 0 || stats.read_cache_file_directly_timer != 0 ||
139
3.06k
           stats.cache_get_or_set_timer != 0 || stats.lock_wait_timer != 0 ||
140
3.06k
           stats.get_timer != 0 || stats.set_timer != 0 ||
141
3.06k
           stats.inverted_index_num_local_io_total != 0 ||
142
3.06k
           stats.inverted_index_num_remote_io_total != 0 ||
143
3.06k
           stats.inverted_index_num_peer_io_total != 0 ||
144
3.06k
           stats.inverted_index_bytes_read_from_local != 0 ||
145
3.06k
           stats.inverted_index_bytes_read_from_remote != 0 ||
146
3.06k
           stats.inverted_index_bytes_read_from_peer != 0 ||
147
3.06k
           stats.inverted_index_local_io_timer != 0 || stats.inverted_index_remote_io_timer != 0 ||
148
3.06k
           stats.inverted_index_peer_io_timer != 0 || stats.inverted_index_io_timer != 0;
149
3.06k
}
150
151
1.53k
Status OlapScanner::_prepare_impl() {
152
1.53k
    auto* local_state = static_cast<OlapScanLocalState*>(_local_state);
153
1.53k
    auto& tablet = _tablet_reader_params.tablet;
154
1.53k
    auto& tablet_schema = _tablet_reader_params.tablet_schema;
155
1.53k
    DBUG_EXECUTE_IF("CloudTablet.capture_rs_readers.return.e-230", {
156
1.53k
        LOG_WARNING("CloudTablet.capture_rs_readers.return e-230 init")
157
1.53k
                .tag("tablet_id", tablet->tablet_id());
158
1.53k
        return Status::Error<false>(-230, "injected error");
159
1.53k
    });
160
161
1.53k
    for (auto& ctx : local_state->_common_expr_ctxs_push_down) {
162
0
        VExprContextSPtr context;
163
0
        RETURN_IF_ERROR(ctx->clone(_state, context));
164
0
        _common_expr_ctxs_push_down.emplace_back(context);
165
0
        context->prepare_ann_range_search(_vector_search_params);
166
0
    }
167
168
1.53k
    for (auto pair : local_state->_slot_id_to_virtual_column_expr) {
169
        // Scanner will be executed in a different thread, so we need to clone the context.
170
0
        VExprContextSPtr context;
171
0
        RETURN_IF_ERROR(pair.second->clone(_state, context));
172
0
        _slot_id_to_virtual_column_expr[pair.first] = context;
173
0
    }
174
175
1.53k
    _score_runtime = local_state->_score_runtime;
176
    // All scanners share the same ann_topn_runtime.
177
1.53k
    _ann_topn_runtime = local_state->_ann_topn_runtime;
178
179
    // set limit to reduce end of rowset and segment mem use
180
1.53k
    _tablet_reader = std::make_unique<BlockReader>();
181
    // batch size is passed down to segment iterator, use _state->batch_size()
182
    // instead of _parent->limit(), because if _parent->limit() is a very small
183
    // value (e.g. select a from t where a .. and b ... limit 1),
184
    // it will be very slow when reading data in segment iterator
185
1.53k
    _tablet_reader->set_batch_size(_state->batch_size());
186
    // Adaptive batch size: pass byte-budget settings to the storage reader.
187
    // The reader still uses batch_size() as the row ceiling.
188
1.53k
    _tablet_reader->set_preferred_block_size_bytes(_state->preferred_block_size_bytes());
189
1.53k
    {
190
1.53k
        TOlapScanNode& olap_scan_node = local_state->olap_scan_node();
191
1.53k
        TabletSchemaSPtr source_tablet_schema =
192
1.53k
                _tablet_reader_params.reader_type == ReaderType::READER_BINLOG
193
1.53k
                        ? tablet->row_binlog_tablet_schema()
194
1.53k
                        : tablet->tablet_schema();
195
196
1.53k
        tablet_schema = std::make_shared<TabletSchema>();
197
1.53k
        tablet_schema->copy_from(*source_tablet_schema);
198
1.53k
        if (olap_scan_node.__isset.columns_desc && !olap_scan_node.columns_desc.empty() &&
199
1.53k
            olap_scan_node.columns_desc[0].col_unique_id >= 0) {
200
1.53k
            tablet_schema->clear_columns();
201
23.0k
            for (const auto& column_desc : olap_scan_node.columns_desc) {
202
23.0k
                tablet_schema->append_column(TabletColumn(column_desc));
203
23.0k
            }
204
1.53k
            if (olap_scan_node.__isset.schema_version) {
205
1.53k
                tablet_schema->set_schema_version(olap_scan_node.schema_version);
206
1.53k
            }
207
1.53k
        }
208
1.53k
        if (olap_scan_node.__isset.indexes_desc) {
209
1.53k
            tablet_schema->update_indexes_from_thrift(olap_scan_node.indexes_desc);
210
1.53k
        }
211
212
1.53k
        if (_tablet_reader_params.rs_splits.empty()) {
213
            // Non-pipeline mode, Tablet : Scanner = 1 : 1
214
            // acquire tablet rowset readers at the beginning of the scan node
215
            // to prevent this case: when there are lots of olap scanners to run for example 10000
216
            // the rowsets maybe compacted when the last olap scanner starts
217
0
            ReadSource read_source;
218
219
0
            if (config::is_cloud_mode()) {
220
                // FIXME(plat1ko): Avoid pointer cast
221
0
                ExecEnv::GetInstance()->storage_engine().to_cloud().tablet_hotspot().count(*tablet);
222
0
            }
223
224
0
            auto maybe_read_source = tablet->capture_read_source(
225
0
                    _tablet_reader_params.version,
226
0
                    {
227
0
                            .skip_missing_versions = _state->skip_missing_version(),
228
0
                            .enable_fetch_rowsets_from_peers =
229
0
                                    config::enable_fetch_rowsets_from_peer_replicas,
230
0
                            .capture_row_binlog =
231
0
                                    _tablet_reader_params.reader_type == ReaderType::READER_BINLOG,
232
0
                            .enable_prefer_cached_rowset =
233
0
                                    config::is_cloud_mode() ? _state->enable_prefer_cached_rowset()
234
0
                                                            : false,
235
0
                            .query_freshness_tolerance_ms =
236
0
                                    config::is_cloud_mode() ? _state->query_freshness_tolerance_ms()
237
0
                                                            : -1,
238
0
                    });
239
0
            if (!maybe_read_source) {
240
0
                LOG(WARNING) << "fail to init reader. res=" << maybe_read_source.error();
241
0
                return maybe_read_source.error();
242
0
            }
243
0
            read_source = std::move(maybe_read_source.value());
244
245
0
            if (config::enable_mow_verbose_log && tablet->enable_unique_key_merge_on_write()) {
246
0
                LOG_INFO("finish capture_rs_readers for tablet={}, query_id={}",
247
0
                         tablet->tablet_id(), print_id(_state->query_id()));
248
0
            }
249
250
0
            if (!_state->skip_delete_predicate()) {
251
0
                read_source.fill_delete_predicates();
252
0
            }
253
0
            _tablet_reader_params.set_read_source(std::move(read_source));
254
0
        }
255
256
        // Initialize tablet_reader_params
257
1.53k
        RETURN_IF_ERROR(_init_tablet_reader_params(
258
1.53k
                local_state->_parent->cast<OlapScanOperatorX>()._slot_id_to_slot_desc, _key_ranges,
259
1.53k
                local_state->_slot_id_to_predicates, local_state->_push_down_functions));
260
1.53k
    }
261
262
    // add read columns in profile
263
1.53k
    if (_state->enable_profile()) {
264
0
        _profile->add_info_string("ReadColumns",
265
0
                                  read_columns_to_string(tablet_schema, _return_columns));
266
0
    }
267
268
1.53k
    if (_tablet_reader_params.score_runtime) {
269
0
        SCOPED_TIMER(local_state->_statistics_collect_timer);
270
0
        _tablet_reader_params.collection_statistics = std::make_shared<CollectionStatistics>();
271
272
0
        io::IOContext io_ctx {
273
0
                .reader_type = _tablet_reader_params.reader_type,
274
0
                .expiration_time = tablet->ttl_seconds(),
275
0
                .query_id = &_state->query_id(),
276
0
                .file_cache_stats = &_tablet_reader->mutable_stats()->file_cache_stats,
277
0
                .is_inverted_index = true,
278
0
        };
279
280
0
        RETURN_IF_ERROR(_tablet_reader_params.collection_statistics->collect(
281
0
                _state, _tablet_reader_params.rs_splits, _tablet_reader_params.tablet_schema,
282
0
                _tablet_reader_params.common_expr_ctxs_push_down, &io_ctx));
283
0
    }
284
285
1.53k
    _has_prepared = true;
286
1.53k
    return Status::OK();
287
1.53k
}
288
289
1.52k
Status OlapScanner::_open_impl(RuntimeState* state) {
290
1.52k
    RETURN_IF_ERROR(Scanner::_open_impl(state));
291
1.52k
    SCOPED_TIMER(_local_state->cast<OlapScanLocalState>()._reader_init_timer);
292
293
1.52k
    auto res = _tablet_reader->init(_tablet_reader_params);
294
1.52k
    if (!res.ok()) {
295
0
        res.append("failed to initialize storage reader. tablet=" +
296
0
                   std::to_string(_tablet_reader_params.tablet->tablet_id()) +
297
0
                   ", backend=" + BackendOptions::get_localhost());
298
0
        return res;
299
0
    }
300
301
    // Do not hold rs_splits any more to release memory.
302
1.52k
    _tablet_reader_params.rs_splits.clear();
303
304
1.52k
    return Status::OK();
305
1.52k
}
306
307
// it will be called under tablet read lock because capture rs readers need
308
Status OlapScanner::_init_tablet_reader_params(
309
        const phmap::flat_hash_map<int, SlotDescriptor*>& slot_id_to_slot_desc,
310
        const std::vector<OlapScanRange*>& key_ranges,
311
        const phmap::flat_hash_map<int, std::vector<std::shared_ptr<ColumnPredicate>>>&
312
                slot_to_predicates,
313
1.53k
        const std::vector<FunctionFilter>& function_filters) {
314
    // if the table with rowset [0-x] or [0-1] [2-y], and [0-1] is empty
315
1.53k
    const bool single_version = _tablet_reader_params.has_single_version();
316
317
1.53k
    auto* olap_local_state = static_cast<OlapScanLocalState*>(_local_state);
318
1.53k
    bool read_mor_as_dup = olap_local_state->olap_scan_node().__isset.read_mor_as_dup &&
319
1.53k
                           olap_local_state->olap_scan_node().read_mor_as_dup;
320
1.53k
    if (_state->skip_storage_engine_merge() || read_mor_as_dup) {
321
0
        _tablet_reader_params.direct_mode = true;
322
0
        _tablet_reader_params.aggregation = true;
323
1.53k
    } else {
324
1.53k
        auto push_down_agg_type = _local_state->get_push_down_agg_type();
325
1.53k
        _tablet_reader_params.direct_mode = _tablet_reader_params.aggregation || single_version ||
326
1.53k
                                            (push_down_agg_type != TPushAggOp::NONE &&
327
0
                                             push_down_agg_type != TPushAggOp::COUNT_ON_INDEX);
328
1.53k
    }
329
330
1.53k
    _tablet_reader_params.filled_columns.clear();
331
1.53k
    RETURN_IF_ERROR(_init_variant_columns());
332
1.53k
    RETURN_IF_ERROR(_init_return_columns());
333
334
1.53k
    _tablet_reader_params.push_down_agg_type_opt = _local_state->get_push_down_agg_type();
335
336
1.53k
    _tablet_reader_params.common_expr_ctxs_push_down = _common_expr_ctxs_push_down;
337
1.53k
    _tablet_reader_params.virtual_column_exprs = _virtual_column_exprs;
338
1.53k
    _tablet_reader_params.score_runtime = _score_runtime;
339
1.53k
    _tablet_reader_params.output_columns = ((OlapScanLocalState*)_local_state)->_output_column_ids;
340
1.53k
    _tablet_reader_params.ann_topn_runtime = _ann_topn_runtime;
341
1.53k
    for (const auto& ele : ((OlapScanLocalState*)_local_state)->_cast_types_for_variants) {
342
0
        _tablet_reader_params.target_cast_type_for_variants[ele.first] = ele.second;
343
0
    };
344
1.53k
    auto& tablet_schema = _tablet_reader_params.tablet_schema;
345
9.76k
    for (auto& predicates : slot_to_predicates) {
346
9.76k
        const int sid = predicates.first;
347
9.76k
        DCHECK(slot_id_to_slot_desc.contains(sid));
348
9.76k
        int32_t index =
349
9.76k
                tablet_schema->field_index(slot_id_to_slot_desc.find(sid)->second->col_name());
350
9.76k
        if (index < 0) {
351
0
            throw Exception(
352
0
                    Status::InternalError("Column {} not found in tablet schema",
353
0
                                          slot_id_to_slot_desc.find(sid)->second->col_name()));
354
0
        }
355
9.76k
        for (auto& predicate : predicates.second) {
356
812
            _tablet_reader_params.predicates.push_back(predicate->clone(index));
357
812
        }
358
9.76k
    }
359
360
1.53k
    std::copy(function_filters.cbegin(), function_filters.cend(),
361
1.53k
              std::inserter(_tablet_reader_params.function_filters,
362
1.53k
                            _tablet_reader_params.function_filters.begin()));
363
364
    // Merge the columns in delete predicate that not in latest schema in to current tablet schema
365
1.53k
    for (auto& del_pred : _tablet_reader_params.delete_predicates) {
366
0
        tablet_schema->merge_dropped_columns(*del_pred->tablet_schema());
367
0
    }
368
369
    // Push key ranges to the tablet reader.
370
    // Skip the "full scan" placeholder (has_lower_bound == false) — when no key
371
    // predicates exist, start_key/end_key remain empty and the reader does a full scan.
372
1.53k
    for (auto* key_range : key_ranges) {
373
1.27k
        if (!key_range->has_lower_bound) {
374
484
            continue;
375
484
        }
376
377
794
        _tablet_reader_params.start_key_include = key_range->begin_include;
378
794
        _tablet_reader_params.end_key_include = key_range->end_include;
379
380
794
        _tablet_reader_params.start_key.push_back(key_range->begin_scan_range);
381
794
        _tablet_reader_params.end_key.push_back(key_range->end_scan_range);
382
794
    }
383
384
1.53k
    _tablet_reader_params.profile = _local_state->custom_profile();
385
1.53k
    _tablet_reader_params.runtime_state = _state;
386
387
1.53k
    _tablet_reader_params.origin_return_columns = &_return_columns;
388
1.53k
    _tablet_reader_params.tablet_columns_convert_to_null_set = &_tablet_columns_convert_to_null_set;
389
390
1.53k
    if (_tablet_reader_params.direct_mode) {
391
1.53k
        _tablet_reader_params.return_columns = _return_columns;
392
1.53k
    } else {
393
        // we need to fetch all key columns to do the right aggregation on storage engine side.
394
0
        for (size_t i = 0; i < tablet_schema->num_key_columns(); ++i) {
395
0
            _tablet_reader_params.return_columns.push_back(i);
396
0
        }
397
0
        for (auto index : _return_columns) {
398
0
            if (tablet_schema->column(index).is_key()) {
399
0
                continue;
400
0
            }
401
0
            _tablet_reader_params.return_columns.push_back(index);
402
0
        }
403
        // expand the sequence column
404
0
        if (tablet_schema->has_sequence_col() || tablet_schema->has_seq_map()) {
405
0
            bool has_replace_col = false;
406
0
            for (auto col : _return_columns) {
407
0
                if (tablet_schema->column(col).aggregation() ==
408
0
                    FieldAggregationMethod::OLAP_FIELD_AGGREGATION_REPLACE) {
409
0
                    has_replace_col = true;
410
0
                    break;
411
0
                }
412
0
            }
413
0
            if (auto sequence_col_idx = tablet_schema->sequence_col_idx();
414
0
                has_replace_col && tablet_schema->has_sequence_col() &&
415
0
                std::find(_return_columns.begin(), _return_columns.end(), sequence_col_idx) ==
416
0
                        _return_columns.end()) {
417
0
                _tablet_reader_params.return_columns.push_back(sequence_col_idx);
418
0
            }
419
0
            if (has_replace_col) {
420
0
                const auto& val_to_seq = tablet_schema->value_col_idx_to_seq_col_idx();
421
0
                std::set<uint32_t> return_seq_columns;
422
423
0
                for (auto col : _tablet_reader_params.return_columns) {
424
                    // we need to add the necessary sequence column in _return_columns, and
425
                    // Avoid adding the same seq column twice
426
0
                    const auto val_iter = val_to_seq.find(col);
427
0
                    if (val_iter != val_to_seq.end()) {
428
0
                        auto seq = val_iter->second;
429
0
                        if (std::find(_tablet_reader_params.return_columns.begin(),
430
0
                                      _tablet_reader_params.return_columns.end(),
431
0
                                      seq) == _tablet_reader_params.return_columns.end()) {
432
0
                            return_seq_columns.insert(seq);
433
0
                        }
434
0
                    }
435
0
                }
436
0
                _tablet_reader_params.return_columns.insert(
437
0
                        std::end(_tablet_reader_params.return_columns),
438
0
                        std::begin(return_seq_columns), std::end(return_seq_columns));
439
0
            }
440
0
        }
441
0
    }
442
443
1.53k
    _tablet_reader_params.use_page_cache = _state->enable_page_cache();
444
445
1.53k
    DBUG_EXECUTE_IF("NewOlapScanner::_init_tablet_reader_params.block", DBUG_BLOCK);
446
447
1.53k
    if (!_state->skip_storage_engine_merge()) {
448
1.53k
        auto* olap_scan_local_state = (OlapScanLocalState*)_local_state;
449
1.53k
        TOlapScanNode& olap_scan_node = olap_scan_local_state->olap_scan_node();
450
451
        // Set MOR value predicate pushdown flag
452
1.53k
        if (olap_scan_node.__isset.enable_mor_value_predicate_pushdown &&
453
1.53k
            olap_scan_node.enable_mor_value_predicate_pushdown) {
454
0
            _tablet_reader_params.enable_mor_value_predicate_pushdown = true;
455
0
        }
456
457
1.53k
        const bool has_key_topn =
458
1.53k
                olap_scan_node.__isset.sort_info && !olap_scan_node.sort_info.is_asc_order.empty();
459
1.53k
        if (has_key_topn) {
460
0
            _limit = _local_state->limit_per_scanner();
461
0
        }
462
463
1.53k
        const bool no_runtime_filters = _total_rf_num == 0;
464
1.53k
        const bool segment_limit_enabled = _state->enable_segment_limit_pushdown();
465
1.53k
        const bool storage_no_merge = olap_scan_local_state->_storage_no_merge();
466
467
1.53k
        if (_limit > 0 && no_runtime_filters && segment_limit_enabled && storage_no_merge) {
468
0
            for (const auto& conjunct : _conjuncts) {
469
0
                DORIS_CHECK(!olap_scan_local_state->_check_expr_storage_filter(
470
0
                        conjunct->root(), OlapScanLocalState::ExprStorageFilterCheckMode::
471
0
                                                  HAS_SEGMENT_EVALUABLE_EXPR));
472
0
            }
473
0
        }
474
475
        // Segment LIMIT has only two legal states: completely disabled, or enabled after every
476
        // row-filtering conjunct has become a storage predicate or SegmentIterator common expr.
477
1.53k
        const bool can_push_down_segment_limit = _limit > 0 && no_runtime_filters &&
478
1.53k
                                                 _conjuncts.empty() && segment_limit_enabled &&
479
1.53k
                                                 storage_no_merge;
480
1.53k
        if (can_push_down_segment_limit) {
481
0
            if (has_key_topn) {
482
0
                _tablet_reader_params.read_orderby_key = true;
483
0
                if (!olap_scan_node.sort_info.is_asc_order[0]) {
484
0
                    _tablet_reader_params.read_orderby_key_reverse = true;
485
0
                }
486
0
                _tablet_reader_params.read_orderby_key_num_prefix_columns =
487
0
                        olap_scan_node.sort_info.is_asc_order.size();
488
0
                _tablet_reader_params.read_orderby_key_limit = _limit;
489
0
            } else {
490
0
                _tablet_reader_params.general_read_limit = _limit;
491
0
            }
492
0
        }
493
494
1.53k
        if (_tablet_reader_params.read_orderby_key_limit > 0 ||
495
1.53k
            _tablet_reader_params.general_read_limit > 0) {
496
0
            DORIS_CHECK(can_push_down_segment_limit);
497
0
            DORIS_CHECK(_conjuncts.empty());
498
0
        }
499
500
        // A key TopN scan cannot share the plain LIMIT early-stop counter. If
501
        // storage TopN is pushed down, each scanner must produce its full local
502
        // candidates. If it is not pushed down for any reason, the upper TopN
503
        // still needs all rows from the scan.
504
1.53k
        if (has_key_topn) {
505
0
            _shared_scan_limit = nullptr;
506
0
            if (_tablet_reader_params.read_orderby_key_limit == 0) {
507
0
                _limit = -1;
508
0
            }
509
0
        }
510
        // Note: _shared_scan_limit is intentionally not pushed into the
511
        // storage layer. SegmentIterator's _process_eof() is irreversible,
512
        // so a concurrently-decremented atomic could reach 0 while a segment
513
        // still has data needed by other scanners.
514
515
        // set push down topn filter
516
1.53k
        _tablet_reader_params.topn_filter_source_node_ids =
517
1.53k
                olap_scan_local_state->get_topn_filter_source_node_ids(_state, true);
518
1.53k
        if (!_tablet_reader_params.topn_filter_source_node_ids.empty()) {
519
0
            _tablet_reader_params.topn_filter_target_node_id =
520
0
                    olap_scan_local_state->parent()->node_id();
521
0
        }
522
1.53k
    }
523
524
    // If this is a Two-Phase read query, and we need to delay the release of Rowset
525
    // by rowset->update_delayed_expired_timestamp().This could expand the lifespan of Rowset
526
1.53k
    if (tablet_schema->field_index(BeConsts::ROWID_COL) >= 0) {
527
0
        constexpr static int delayed_s = 60;
528
0
        for (auto rs_reader : _tablet_reader_params.rs_splits) {
529
0
            uint64_t delayed_expired_timestamp =
530
0
                    UnixSeconds() + _tablet_reader_params.runtime_state->execution_timeout() +
531
0
                    delayed_s;
532
0
            rs_reader.rs_reader->rowset()->update_delayed_expired_timestamp(
533
0
                    delayed_expired_timestamp);
534
0
            ExecEnv::GetInstance()->storage_engine().add_quering_rowset(
535
0
                    rs_reader.rs_reader->rowset());
536
0
        }
537
0
    }
538
539
1.53k
    if (tablet_schema->has_global_row_id()) {
540
0
        auto& id_file_map = _state->get_id_file_map();
541
0
        for (auto rs_reader : _tablet_reader_params.rs_splits) {
542
0
            id_file_map->add_temp_rowset(rs_reader.rs_reader->rowset());
543
0
        }
544
0
    }
545
546
1.53k
    return Status::OK();
547
1.53k
}
548
549
1.53k
Status OlapScanner::_init_variant_columns() {
550
1.53k
    auto& tablet_schema = _tablet_reader_params.tablet_schema;
551
1.53k
    if (tablet_schema->num_variant_columns() == 0) {
552
1.53k
        return Status::OK();
553
1.53k
    }
554
    // Parent column has path info to distinction from each other
555
0
    for (auto* slot : _output_tuple_desc->slots()) {
556
0
        if (slot->type()->get_primitive_type() == PrimitiveType::TYPE_VARIANT) {
557
            // Such columns are not exist in frontend schema info, so we need to
558
            // add them into tablet_schema for later column indexing.
559
0
            const auto& dt_variant =
560
0
                    assert_cast<const DataTypeVariant&>(*remove_nullable(slot->type()));
561
0
            TabletColumn subcol = TabletColumn::create_materialized_variant_column(
562
0
                    tablet_schema->column_by_uid(slot->col_unique_id()).name_lower_case(),
563
0
                    slot->column_paths(), slot->col_unique_id(),
564
0
                    dt_variant.variant_max_subcolumns_count(), dt_variant.enable_doc_mode());
565
0
            if (tablet_schema->field_index(*subcol.path_info_ptr()) < 0) {
566
0
                tablet_schema->append_column(subcol, TabletSchema::ColumnType::VARIANT);
567
0
            }
568
0
        }
569
0
    }
570
0
    variant_util::inherit_column_attributes(tablet_schema);
571
0
    return Status::OK();
572
1.53k
}
573
574
1.53k
Status OlapScanner::_init_return_columns() {
575
12.6k
    for (auto* slot : _output_tuple_desc->slots()) {
576
        // variant column using path to index a column
577
12.6k
        int32_t index = 0;
578
12.6k
        auto& tablet_schema = _tablet_reader_params.tablet_schema;
579
12.6k
        if (slot->type()->get_primitive_type() == PrimitiveType::TYPE_VARIANT) {
580
0
            index = tablet_schema->field_index(PathInData(
581
0
                    tablet_schema->column_by_uid(slot->col_unique_id()).name_lower_case(),
582
0
                    slot->column_paths()));
583
12.6k
        } else {
584
12.6k
            index = slot->col_unique_id() >= 0 ? tablet_schema->field_index(slot->col_unique_id())
585
12.6k
                                               : tablet_schema->field_index(slot->col_name());
586
12.6k
        }
587
588
12.6k
        if (index < 0) {
589
0
            return Status::InternalError(
590
0
                    "field name is invalid. field={}, field_name_to_index={}, col_unique_id={}",
591
0
                    slot->col_name(), tablet_schema->get_all_field_names(), slot->col_unique_id());
592
0
        }
593
594
12.6k
        if (slot->get_virtual_column_expr()) {
595
0
            ColumnId virtual_column_cid = index;
596
0
            _virtual_column_exprs[virtual_column_cid] = _slot_id_to_virtual_column_expr[slot->id()];
597
598
0
            VLOG_DEBUG << fmt::format("Virtual column, slot id: {}, cid {}, type: {}", slot->id(),
599
0
                                      virtual_column_cid, slot->get_data_type_ptr()->get_name());
600
0
        }
601
602
12.6k
        const auto& column = tablet_schema->column(index);
603
12.6k
        auto* olap_local_state = static_cast<OlapScanLocalState*>(_local_state);
604
12.6k
        const auto& olap_scan_node = olap_local_state->olap_scan_node();
605
12.6k
        if (olap_scan_node.__isset.filled_key_column_slot_ids &&
606
12.6k
            olap_scan_node.filled_key_column_slot_ids.contains(slot->id())) {
607
0
            DORIS_CHECK(column.is_key());
608
0
            if (_tablet_reader_params.direct_mode) {
609
0
                _tablet_reader_params.filled_columns.insert(index);
610
0
            }
611
0
        }
612
12.6k
        int32_t unique_id =
613
12.6k
                column.unique_id() >= 0 ? column.unique_id() : column.parent_unique_id();
614
12.6k
        if (!slot->all_access_paths().empty()) {
615
226
            _tablet_reader_params.all_access_paths.insert({unique_id, slot->all_access_paths()});
616
226
        }
617
618
12.6k
        if (!slot->predicate_access_paths().empty()) {
619
0
            _tablet_reader_params.predicate_access_paths.insert(
620
0
                    {unique_id, slot->predicate_access_paths()});
621
0
        }
622
623
12.6k
        if ((slot->type()->get_primitive_type() == PrimitiveType::TYPE_STRUCT ||
624
12.6k
             slot->type()->get_primitive_type() == PrimitiveType::TYPE_MAP ||
625
12.6k
             slot->type()->get_primitive_type() == PrimitiveType::TYPE_ARRAY) &&
626
12.6k
            !slot->all_access_paths().empty()) {
627
0
            tablet_schema->add_pruned_columns_data_type(column.unique_id(), slot->type());
628
0
        }
629
630
12.6k
        _return_columns.push_back(index);
631
12.6k
        if (slot->is_nullable() && !tablet_schema->column(index).is_nullable()) {
632
0
            _tablet_columns_convert_to_null_set.emplace(index);
633
12.6k
        } else if (!slot->is_nullable() && tablet_schema->column(index).is_nullable()) {
634
0
            return Status::Error<ErrorCode::INVALID_SCHEMA>(
635
0
                    "slot(id: {}, name: {})'s nullable does not match "
636
0
                    "column(tablet id: {}, index: {}, name: {}) ",
637
0
                    slot->id(), slot->col_name(), tablet_schema->table_id(), index,
638
0
                    tablet_schema->column(index).name());
639
0
        }
640
12.6k
    }
641
642
1.53k
    if (_return_columns.empty()) {
643
0
        return Status::InternalError("failed to build storage scanner, no materialized slot!");
644
0
    }
645
646
1.53k
    return Status::OK();
647
1.53k
}
648
649
3.06k
bool OlapScanner::check_partition_pruned() const {
650
3.06k
    if (!_local_state) {
651
0
        return false;
652
0
    }
653
3.06k
    return _local_state->is_partition_pruned(_tablet_reader_params.tablet->partition_id());
654
3.06k
}
655
656
1.53k
doris::TabletStorageType OlapScanner::get_storage_type() {
657
1.53k
    if (config::is_cloud_mode()) {
658
        // we don't have cold storage in cloud mode, all storage is treated as local
659
0
        return doris::TabletStorageType::STORAGE_TYPE_LOCAL;
660
0
    }
661
1.53k
    int local_reader = 0;
662
3.59k
    for (const auto& reader : _tablet_reader_params.rs_splits) {
663
3.59k
        local_reader += reader.rs_reader->rowset()->is_local();
664
3.59k
    }
665
1.53k
    int total_reader = _tablet_reader_params.rs_splits.size();
666
667
1.53k
    if (local_reader == total_reader) {
668
1.53k
        return doris::TabletStorageType::STORAGE_TYPE_LOCAL;
669
1.53k
    } else if (local_reader == 0) {
670
0
        return doris::TabletStorageType::STORAGE_TYPE_REMOTE;
671
0
    }
672
0
    return doris::TabletStorageType::STORAGE_TYPE_REMOTE_AND_LOCAL;
673
1.53k
}
674
675
2.67k
Status OlapScanner::_get_block_impl(RuntimeState* state, Block* block, bool* eof) {
676
    // Read one block from block reader
677
    // ATTN: Here we need to let the _get_block_impl method guarantee the semantics of the interface,
678
    // that is, eof can be set to true only when the returned block is empty.
679
2.67k
    RETURN_IF_ERROR(_tablet_reader->next_block_with_aggregation(block, eof));
680
2.67k
    if (block->rows() > 0) {
681
1.14k
        _tablet_reader_params.tablet->read_block_count.fetch_add(1, std::memory_order_relaxed);
682
1.14k
        *eof = false;
683
1.14k
    }
684
2.67k
#ifndef NDEBUG
685
2.67k
    RETURN_IF_ERROR(_check_ann_cache_hit_debug_points(_tablet_reader->stats()));
686
2.67k
#endif
687
2.67k
    return Status::OK();
688
2.67k
}
689
690
1.69k
Status OlapScanner::close(RuntimeState* state) {
691
1.69k
    if (!_try_close()) {
692
150
        return Status::OK();
693
150
    }
694
1.54k
    RETURN_IF_ERROR(Scanner::close(state));
695
1.54k
    return Status::OK();
696
1.54k
}
697
698
1.53k
void OlapScanner::update_realtime_counters() {
699
1.53k
    if (!_has_prepared) {
700
        // Counter update need prepare successfully, or it maybe core. For example, olap scanner
701
        // will open tablet reader during prepare, if not prepare successfully, tablet reader == nullptr.
702
0
        return;
703
0
    }
704
1.53k
    OlapScanLocalState* local_state = static_cast<OlapScanLocalState*>(_local_state);
705
1.53k
    const OlapReaderStatistics& stats = _tablet_reader->stats();
706
1.53k
    COUNTER_UPDATE(local_state->_read_compressed_counter, stats.compressed_bytes_read);
707
1.53k
    COUNTER_UPDATE(local_state->_read_uncompressed_counter, stats.uncompressed_bytes_read);
708
1.53k
    COUNTER_UPDATE(local_state->_scan_bytes, stats.uncompressed_bytes_read);
709
1.53k
    COUNTER_UPDATE(local_state->_scan_rows, stats.raw_rows_read);
710
711
    // Make sure the scan bytes and scan rows counter in audit log is the same as the counter in
712
    // doris metrics.
713
    // ScanBytes is the uncompressed bytes read from local + remote
714
    // bytes_read_from_local is the compressed bytes read from local
715
    // bytes_read_from_remote is the compressed bytes read from remote
716
    // scan bytes > bytes_read_from_local + bytes_read_from_remote
717
1.53k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_rows(stats.raw_rows_read);
718
1.53k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes(
719
1.53k
            stats.uncompressed_bytes_read);
720
721
    // In case of no cache, we still need to update the IO stats. uncompressed bytes read == local + remote
722
1.53k
    if (stats.file_cache_stats.bytes_read_from_local == 0 &&
723
1.53k
        stats.file_cache_stats.bytes_read_from_remote == 0) {
724
1.53k
        _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_local_storage(
725
1.53k
                stats.compressed_bytes_read);
726
1.53k
        DorisMetrics::instance()->query_scan_bytes_from_local->increment(
727
1.53k
                stats.compressed_bytes_read);
728
1.53k
    } else {
729
0
        _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_local_storage(
730
0
                stats.file_cache_stats.bytes_read_from_local);
731
0
        _state->get_query_ctx()
732
0
                ->resource_ctx()
733
0
                ->io_context()
734
0
                ->update_scan_bytes_from_remote_storage(
735
0
                        stats.file_cache_stats.bytes_read_from_remote);
736
737
0
        DorisMetrics::instance()->query_scan_bytes_from_local->increment(
738
0
                stats.file_cache_stats.bytes_read_from_local);
739
0
        DorisMetrics::instance()->query_scan_bytes_from_remote->increment(
740
0
                stats.file_cache_stats.bytes_read_from_remote);
741
0
    }
742
743
1.53k
    if (has_file_cache_statistics(stats.file_cache_stats)) {
744
0
        io::FileCacheProfileReporter cache_profile(local_state->_segment_profile.get());
745
0
        cache_profile.update(&stats.file_cache_stats);
746
0
        _state->get_query_ctx()->resource_ctx()->io_context()->update_bytes_write_into_cache(
747
0
                stats.file_cache_stats.bytes_write_into_cache);
748
0
    }
749
750
1.53k
    _tablet_reader->mutable_stats()->compressed_bytes_read = 0;
751
1.53k
    _tablet_reader->mutable_stats()->uncompressed_bytes_read = 0;
752
1.53k
    _tablet_reader->mutable_stats()->raw_rows_read = 0;
753
1.53k
    _tablet_reader->mutable_stats()->file_cache_stats = {};
754
1.53k
}
755
756
1.53k
void OlapScanner::_collect_profile_before_close() {
757
    //  Please don't directly enable the profile here, we need to set QueryStatistics using the counter inside.
758
1.53k
    if (_has_updated_counter) {
759
0
        return;
760
0
    }
761
1.53k
    _has_updated_counter = true;
762
1.53k
    _tablet_reader->update_profile(_profile);
763
764
1.53k
    Scanner::_collect_profile_before_close();
765
766
    // Update counters for OlapScanner
767
    // Update counters from tablet reader's stats
768
1.53k
    auto& stats = _tablet_reader->stats();
769
1.53k
    auto* local_state = (OlapScanLocalState*)_local_state;
770
1.53k
    COUNTER_UPDATE(local_state->_io_timer, stats.io_ns);
771
1.53k
    COUNTER_UPDATE(local_state->_read_compressed_counter, stats.compressed_bytes_read);
772
1.53k
    COUNTER_UPDATE(local_state->_scan_bytes, stats.uncompressed_bytes_read);
773
1.53k
    COUNTER_UPDATE(local_state->_decompressor_timer, stats.decompress_ns);
774
1.53k
    COUNTER_UPDATE(local_state->_read_uncompressed_counter, stats.uncompressed_bytes_read);
775
1.53k
    COUNTER_UPDATE(local_state->_block_load_timer, stats.block_load_ns);
776
1.53k
    COUNTER_UPDATE(local_state->_block_load_counter, stats.blocks_load);
777
1.53k
    COUNTER_UPDATE(local_state->_block_fetch_timer, stats.block_fetch_ns);
778
1.53k
    COUNTER_UPDATE(local_state->_delete_bitmap_get_agg_timer, stats.delete_bitmap_get_agg_ns);
779
1.53k
    COUNTER_UPDATE(local_state->_scan_rows, stats.raw_rows_read);
780
1.53k
    COUNTER_UPDATE(local_state->_vec_cond_timer, stats.vec_cond_ns);
781
1.53k
    COUNTER_UPDATE(local_state->_short_cond_timer, stats.short_cond_ns);
782
1.53k
    COUNTER_UPDATE(local_state->_expr_filter_timer, stats.expr_filter_ns);
783
1.53k
    COUNTER_UPDATE(local_state->_block_init_timer, stats.block_init_ns);
784
1.53k
    COUNTER_UPDATE(local_state->_block_init_seek_timer, stats.block_init_seek_ns);
785
1.53k
    COUNTER_UPDATE(local_state->_block_init_seek_counter, stats.block_init_seek_num);
786
1.53k
    COUNTER_UPDATE(local_state->_segment_generate_row_range_by_keys_timer,
787
1.53k
                   stats.generate_row_ranges_by_keys_ns);
788
1.53k
    COUNTER_UPDATE(local_state->_segment_generate_row_range_by_column_conditions_timer,
789
1.53k
                   stats.generate_row_ranges_by_column_conditions_ns);
790
1.53k
    COUNTER_UPDATE(local_state->_segment_generate_row_range_by_bf_timer,
791
1.53k
                   stats.generate_row_ranges_by_bf_ns);
792
1.53k
    COUNTER_UPDATE(local_state->_collect_iterator_merge_next_timer,
793
1.53k
                   stats.collect_iterator_merge_next_timer);
794
1.53k
    COUNTER_UPDATE(local_state->_segment_generate_row_range_by_zonemap_timer,
795
1.53k
                   stats.generate_row_ranges_by_zonemap_ns);
796
1.53k
    COUNTER_UPDATE(local_state->_segment_generate_row_range_by_dict_timer,
797
1.53k
                   stats.generate_row_ranges_by_dict_ns);
798
1.53k
    COUNTER_UPDATE(local_state->_predicate_column_read_timer, stats.predicate_column_read_ns);
799
1.53k
    COUNTER_UPDATE(local_state->_non_predicate_column_read_timer, stats.non_predicate_read_ns);
800
1.53k
    COUNTER_UPDATE(local_state->_predicate_column_read_seek_timer,
801
1.53k
                   stats.predicate_column_read_seek_ns);
802
1.53k
    COUNTER_UPDATE(local_state->_predicate_column_read_seek_counter,
803
1.53k
                   stats.predicate_column_read_seek_num);
804
1.53k
    COUNTER_UPDATE(local_state->_lazy_read_timer, stats.lazy_read_ns);
805
1.53k
    COUNTER_UPDATE(local_state->_lazy_read_seek_timer, stats.block_lazy_read_seek_ns);
806
1.53k
    COUNTER_UPDATE(local_state->_lazy_read_seek_counter, stats.block_lazy_read_seek_num);
807
1.53k
    COUNTER_UPDATE(local_state->_output_col_timer, stats.output_col_ns);
808
1.53k
    COUNTER_UPDATE(local_state->_rows_vec_cond_filtered_counter, stats.rows_vec_cond_filtered);
809
1.53k
    COUNTER_UPDATE(local_state->_rows_short_circuit_cond_filtered_counter,
810
1.53k
                   stats.rows_short_circuit_cond_filtered);
811
1.53k
    COUNTER_UPDATE(local_state->_rows_expr_cond_filtered_counter, stats.rows_expr_cond_filtered);
812
1.53k
    COUNTER_UPDATE(local_state->_rows_vec_cond_input_counter, stats.vec_cond_input_rows);
813
1.53k
    COUNTER_UPDATE(local_state->_rows_short_circuit_cond_input_counter,
814
1.53k
                   stats.short_circuit_cond_input_rows);
815
1.53k
    COUNTER_UPDATE(local_state->_rows_expr_cond_input_counter, stats.expr_cond_input_rows);
816
1.53k
    COUNTER_UPDATE(local_state->_stats_filtered_counter, stats.rows_stats_filtered);
817
1.53k
    COUNTER_UPDATE(local_state->_stats_rp_filtered_counter, stats.rows_stats_rp_filtered);
818
1.53k
    COUNTER_UPDATE(local_state->_dict_filtered_counter, stats.segment_dict_filtered);
819
1.53k
    COUNTER_UPDATE(local_state->_bf_filtered_counter, stats.rows_bf_filtered);
820
1.53k
    COUNTER_UPDATE(local_state->_del_filtered_counter, stats.rows_del_filtered);
821
1.53k
    COUNTER_UPDATE(local_state->_del_filtered_counter, stats.rows_del_by_bitmap);
822
1.53k
    COUNTER_UPDATE(local_state->_del_filtered_counter, stats.rows_vec_del_cond_filtered);
823
1.53k
    COUNTER_UPDATE(local_state->_conditions_filtered_counter, stats.rows_conditions_filtered);
824
1.53k
    COUNTER_UPDATE(local_state->_key_range_filtered_counter, stats.rows_key_range_filtered);
825
1.53k
    COUNTER_UPDATE(local_state->_total_pages_num_counter, stats.total_pages_num);
826
1.53k
    COUNTER_UPDATE(local_state->_cached_pages_num_counter, stats.cached_pages_num);
827
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_filter_counter, stats.rows_inverted_index_filtered);
828
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_filter_timer, stats.inverted_index_filter_timer);
829
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_query_cache_hit_counter,
830
1.53k
                   stats.inverted_index_query_cache_hit);
831
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_query_cache_miss_counter,
832
1.53k
                   stats.inverted_index_query_cache_miss);
833
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_query_timer, stats.inverted_index_query_timer);
834
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_query_null_bitmap_timer,
835
1.53k
                   stats.inverted_index_query_null_bitmap_timer);
836
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_query_bitmap_copy_timer,
837
1.53k
                   stats.inverted_index_query_bitmap_copy_timer);
838
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_searcher_open_timer,
839
1.53k
                   stats.inverted_index_searcher_open_timer);
840
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_searcher_search_timer,
841
1.53k
                   stats.inverted_index_searcher_search_timer);
842
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_searcher_search_init_timer,
843
1.53k
                   stats.inverted_index_searcher_search_init_timer);
844
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_searcher_search_exec_timer,
845
1.53k
                   stats.inverted_index_searcher_search_exec_timer);
846
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_searcher_cache_hit_counter,
847
1.53k
                   stats.inverted_index_searcher_cache_hit);
848
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_searcher_cache_miss_counter,
849
1.53k
                   stats.inverted_index_searcher_cache_miss);
850
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_downgrade_count_counter,
851
1.53k
                   stats.inverted_index_downgrade_count);
852
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_analyzer_timer,
853
1.53k
                   stats.inverted_index_analyzer_timer);
854
1.53k
    COUNTER_UPDATE(local_state->_inverted_index_lookup_timer, stats.inverted_index_lookup_timer);
855
1.53k
    COUNTER_UPDATE(local_state->_variant_scan_sparse_column_timer,
856
1.53k
                   stats.variant_scan_sparse_column_timer_ns);
857
1.53k
    COUNTER_UPDATE(local_state->_variant_scan_sparse_column_bytes,
858
1.53k
                   stats.variant_scan_sparse_column_bytes);
859
1.53k
    COUNTER_UPDATE(local_state->_variant_fill_path_from_sparse_column_timer,
860
1.53k
                   stats.variant_fill_path_from_sparse_column_timer_ns);
861
1.53k
    COUNTER_UPDATE(local_state->_variant_subtree_default_iter_count,
862
1.53k
                   stats.variant_subtree_default_iter_count);
863
1.53k
    COUNTER_UPDATE(local_state->_variant_subtree_leaf_iter_count,
864
1.53k
                   stats.variant_subtree_leaf_iter_count);
865
1.53k
    COUNTER_UPDATE(local_state->_variant_subtree_hierarchical_iter_count,
866
1.53k
                   stats.variant_subtree_hierarchical_iter_count);
867
1.53k
    COUNTER_UPDATE(local_state->_variant_subtree_sparse_iter_count,
868
1.53k
                   stats.variant_subtree_sparse_iter_count);
869
1.53k
    COUNTER_UPDATE(local_state->_variant_doc_value_column_iter_count,
870
1.53k
                   stats.variant_doc_value_column_iter_count);
871
872
1.53k
    if (stats.adaptive_batch_size_predict_max_rows > 0) {
873
1.04k
        local_state->_adaptive_batch_predict_min_rows_counter->set(
874
1.04k
                stats.adaptive_batch_size_predict_min_rows);
875
1.04k
        local_state->_adaptive_batch_predict_max_rows_counter->set(
876
1.04k
                stats.adaptive_batch_size_predict_max_rows);
877
1.04k
    }
878
879
1.53k
    InvertedIndexProfileReporter inverted_index_profile;
880
1.53k
    inverted_index_profile.update(local_state->_index_filter_profile.get(),
881
1.53k
                                  &stats.inverted_index_stats);
882
883
1.53k
    if (has_file_cache_statistics(stats.file_cache_stats)) {
884
0
        io::FileCacheProfileReporter cache_profile(local_state->_segment_profile.get());
885
0
        cache_profile.update(&stats.file_cache_stats);
886
0
        _state->get_query_ctx()->resource_ctx()->io_context()->update_bytes_write_into_cache(
887
0
                stats.file_cache_stats.bytes_write_into_cache);
888
0
    }
889
1.53k
    COUNTER_UPDATE(local_state->_output_index_result_column_timer,
890
1.53k
                   stats.output_index_result_column_timer);
891
1.53k
    COUNTER_UPDATE(local_state->_filtered_segment_counter, stats.filtered_segment_number);
892
1.53k
    COUNTER_UPDATE(local_state->_total_segment_counter, stats.total_segment_number);
893
1.53k
    COUNTER_UPDATE(local_state->_condition_cache_hit_counter, stats.condition_cache_hit_seg_nums);
894
1.53k
    COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter,
895
1.53k
                   stats.condition_cache_filtered_rows);
896
897
1.53k
    COUNTER_UPDATE(local_state->_tablet_reader_init_timer, stats.tablet_reader_init_timer_ns);
898
1.53k
    COUNTER_UPDATE(local_state->_tablet_reader_capture_rs_readers_timer,
899
1.53k
                   stats.tablet_reader_capture_rs_readers_timer_ns);
900
1.53k
    COUNTER_UPDATE(local_state->_tablet_reader_init_return_columns_timer,
901
1.53k
                   stats.tablet_reader_init_return_columns_timer_ns);
902
1.53k
    COUNTER_UPDATE(local_state->_tablet_reader_init_keys_param_timer,
903
1.53k
                   stats.tablet_reader_init_keys_param_timer_ns);
904
1.53k
    COUNTER_UPDATE(local_state->_tablet_reader_init_orderby_keys_param_timer,
905
1.53k
                   stats.tablet_reader_init_orderby_keys_param_timer_ns);
906
1.53k
    COUNTER_UPDATE(local_state->_tablet_reader_init_conditions_param_timer,
907
1.53k
                   stats.tablet_reader_init_conditions_param_timer_ns);
908
1.53k
    COUNTER_UPDATE(local_state->_tablet_reader_init_delete_condition_param_timer,
909
1.53k
                   stats.tablet_reader_init_delete_condition_param_timer_ns);
910
1.53k
    COUNTER_UPDATE(local_state->_block_reader_vcollect_iter_init_timer,
911
1.53k
                   stats.block_reader_vcollect_iter_init_timer_ns);
912
1.53k
    COUNTER_UPDATE(local_state->_block_reader_rs_readers_init_timer,
913
1.53k
                   stats.block_reader_rs_readers_init_timer_ns);
914
1.53k
    COUNTER_UPDATE(local_state->_block_reader_build_heap_init_timer,
915
1.53k
                   stats.block_reader_build_heap_init_timer_ns);
916
917
1.53k
    COUNTER_UPDATE(local_state->_rowset_reader_get_segment_iterators_timer,
918
1.53k
                   stats.rowset_reader_get_segment_iterators_timer_ns);
919
1.53k
    COUNTER_UPDATE(local_state->_rowset_reader_create_iterators_timer,
920
1.53k
                   stats.rowset_reader_create_iterators_timer_ns);
921
1.53k
    COUNTER_UPDATE(local_state->_rowset_reader_init_iterators_timer,
922
1.53k
                   stats.rowset_reader_init_iterators_timer_ns);
923
1.53k
    COUNTER_UPDATE(local_state->_rowset_reader_load_segments_timer,
924
1.53k
                   stats.rowset_reader_load_segments_timer_ns);
925
926
1.53k
    COUNTER_UPDATE(local_state->_segment_iterator_init_timer, stats.segment_iterator_init_timer_ns);
927
1.53k
    COUNTER_UPDATE(local_state->_segment_iterator_init_return_column_iterators_timer,
928
1.53k
                   stats.segment_iterator_init_return_column_iterators_timer_ns);
929
1.53k
    COUNTER_UPDATE(local_state->_segment_iterator_init_index_iterators_timer,
930
1.53k
                   stats.segment_iterator_init_index_iterators_timer_ns);
931
1.53k
    COUNTER_UPDATE(local_state->_segment_iterator_init_segment_prefetchers_timer,
932
1.53k
                   stats.segment_iterator_init_segment_prefetchers_timer_ns);
933
934
1.53k
    COUNTER_UPDATE(local_state->_segment_create_column_readers_timer,
935
1.53k
                   stats.segment_create_column_readers_timer_ns);
936
1.53k
    COUNTER_UPDATE(local_state->_segment_load_index_timer, stats.segment_load_index_timer_ns);
937
938
    // Update metrics
939
1.53k
    DorisMetrics::instance()->query_scan_bytes->increment(
940
1.53k
            local_state->_read_uncompressed_counter->value());
941
1.53k
    DorisMetrics::instance()->query_scan_rows->increment(local_state->_scan_rows->value());
942
1.53k
    auto& tablet = _tablet_reader_params.tablet;
943
1.53k
    tablet->query_scan_bytes->increment(local_state->_read_uncompressed_counter->value());
944
1.53k
    tablet->query_scan_rows->increment(local_state->_scan_rows->value());
945
1.53k
    tablet->query_scan_count->increment(1);
946
947
1.53k
    COUNTER_UPDATE(local_state->_ann_range_search_filter_counter,
948
1.53k
                   stats.rows_ann_index_range_filtered);
949
1.53k
    COUNTER_UPDATE(local_state->_ann_topn_filter_counter, stats.rows_ann_index_topn_filtered);
950
1.53k
    COUNTER_UPDATE(local_state->_ann_index_load_costs, stats.ann_index_load_ns);
951
1.53k
    COUNTER_UPDATE(local_state->_ann_ivf_on_disk_load_costs, stats.ann_ivf_on_disk_load_ns);
952
1.53k
    COUNTER_UPDATE(local_state->_ann_ivf_on_disk_cache_hit_cnt,
953
1.53k
                   stats.ann_ivf_on_disk_cache_hit_cnt);
954
1.53k
    COUNTER_UPDATE(local_state->_ann_ivf_on_disk_cache_miss_cnt,
955
1.53k
                   stats.ann_ivf_on_disk_cache_miss_cnt);
956
1.53k
    COUNTER_UPDATE(local_state->_ann_range_search_costs, stats.ann_index_range_search_ns);
957
1.53k
    COUNTER_UPDATE(local_state->_ann_range_search_cnt, stats.ann_index_range_search_cnt);
958
1.53k
    COUNTER_UPDATE(local_state->_ann_range_engine_search_costs, stats.ann_range_engine_search_ns);
959
    // Engine prepare before search
960
1.53k
    COUNTER_UPDATE(local_state->_ann_range_pre_process_costs, stats.ann_range_pre_process_ns);
961
    // Post process parent: Doris result process + engine convert
962
1.53k
    COUNTER_UPDATE(local_state->_ann_range_post_process_costs,
963
1.53k
                   stats.ann_range_result_convert_ns + stats.ann_range_engine_convert_ns);
964
    // Engine convert (child under post-process)
965
1.53k
    COUNTER_UPDATE(local_state->_ann_range_engine_convert_costs, stats.ann_range_engine_convert_ns);
966
    // Doris-side result convert (child under post-process)
967
1.53k
    COUNTER_UPDATE(local_state->_ann_range_result_convert_costs, stats.ann_range_result_convert_ns);
968
969
1.53k
    COUNTER_UPDATE(local_state->_ann_topn_search_costs, stats.ann_topn_search_ns);
970
1.53k
    COUNTER_UPDATE(local_state->_ann_topn_search_cnt, stats.ann_index_topn_search_cnt);
971
1.53k
    COUNTER_UPDATE(local_state->_ann_cache_hit_cnt, stats.ann_index_cache_hits);
972
1.53k
    COUNTER_UPDATE(local_state->_ann_range_cache_hit_cnt, stats.ann_index_range_cache_hits);
973
974
    // Detailed ANN timers
975
    // ANN TopN timers with hierarchy
976
    // Engine search time (FAISS)
977
1.53k
    COUNTER_UPDATE(local_state->_ann_topn_engine_search_costs,
978
1.53k
                   stats.ann_index_topn_engine_search_ns);
979
    // Engine prepare time (allocations/buffer setup before search)
980
1.53k
    COUNTER_UPDATE(local_state->_ann_topn_pre_process_costs,
981
1.53k
                   stats.ann_index_topn_engine_prepare_ns);
982
    // Post process parent includes Doris result processing + engine convert
983
1.53k
    COUNTER_UPDATE(local_state->_ann_topn_post_process_costs,
984
1.53k
                   stats.ann_index_topn_result_process_ns + stats.ann_index_topn_engine_convert_ns);
985
    // Engine-side conversion time inside FAISS wrappers (child under post-process)
986
1.53k
    COUNTER_UPDATE(local_state->_ann_topn_engine_convert_costs,
987
1.53k
                   stats.ann_index_topn_engine_convert_ns);
988
989
    // Doris-side result convert costs (show separately as another child counter); use pure process time
990
1.53k
    COUNTER_UPDATE(local_state->_ann_topn_result_convert_costs,
991
1.53k
                   stats.ann_index_topn_result_process_ns);
992
993
1.53k
    COUNTER_UPDATE(local_state->_ann_fallback_brute_force_cnt, stats.ann_fall_back_brute_force_cnt);
994
995
    // Overhead counter removed; precise instrumentation is reported via engine_prepare above.
996
1.53k
}
997
998
#ifndef NDEBUG
999
2.67k
Status OlapScanner::_check_ann_cache_hit_debug_points(const OlapReaderStatistics& stats) {
1000
2.67k
    DBUG_EXECUTE_IF("olap_scanner.ann_topn_cache_hits", {
1001
2.67k
        auto expected_hits = dp->param<int32_t>("expected_hits", -1);
1002
2.67k
        auto min_hits = dp->param<int32_t>("min_hits", -1);
1003
2.67k
        if (expected_hits >= 0 && stats.ann_index_cache_hits != expected_hits) {
1004
2.67k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
1005
2.67k
                    "ann_index_cache_hits: {} not equal to expected: {}",
1006
2.67k
                    stats.ann_index_cache_hits, expected_hits);
1007
2.67k
        }
1008
2.67k
        if (min_hits >= 0 && stats.ann_index_cache_hits < min_hits) {
1009
2.67k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
1010
2.67k
                    "ann_index_cache_hits: {} less than expected min: {}",
1011
2.67k
                    stats.ann_index_cache_hits, min_hits);
1012
2.67k
        }
1013
2.67k
    })
1014
2.67k
    DBUG_EXECUTE_IF("olap_scanner.ann_range_cache_hits", {
1015
2.67k
        auto expected_hits = dp->param<int32_t>("expected_hits", -1);
1016
2.67k
        auto min_hits = dp->param<int32_t>("min_hits", -1);
1017
2.67k
        if (expected_hits >= 0 && stats.ann_index_range_cache_hits != expected_hits) {
1018
2.67k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
1019
2.67k
                    "ann_index_range_cache_hits: {} not equal to expected: {}",
1020
2.67k
                    stats.ann_index_range_cache_hits, expected_hits);
1021
2.67k
        }
1022
2.67k
        if (min_hits >= 0 && stats.ann_index_range_cache_hits < min_hits) {
1023
2.67k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
1024
2.67k
                    "ann_index_range_cache_hits: {} less than expected min: {}",
1025
2.67k
                    stats.ann_index_range_cache_hits, min_hits);
1026
2.67k
        }
1027
2.67k
    })
1028
2.67k
    return Status::OK();
1029
2.67k
}
1030
#endif
1031
1032
#include "common/compile_check_avoid_end.h"
1033
} // namespace doris