Coverage Report

Created: 2026-08-14 19:57

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