Coverage Report

Created: 2026-08-05 03:44

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