Coverage Report

Created: 2026-08-13 19:26

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