Coverage Report

Created: 2026-06-19 20:08

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