Coverage Report

Created: 2026-08-14 11:07

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