Coverage Report

Created: 2026-08-14 11:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/segment_iterator.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 "storage/segment/segment_iterator.h"
19
20
#include <gen_cpp/Exprs_types.h>
21
#include <gen_cpp/Opcodes_types.h>
22
#include <gen_cpp/Types_types.h>
23
#include <gen_cpp/olap_file.pb.h>
24
#include <glog/logging.h>
25
26
#include <algorithm>
27
#include <boost/iterator/iterator_facade.hpp>
28
#include <cassert>
29
#include <cstdint>
30
#include <memory>
31
#include <numeric>
32
#include <optional>
33
#include <set>
34
#include <unordered_map>
35
#include <utility>
36
#include <vector>
37
38
#include "cloud/config.h"
39
#include "common/compiler_util.h" // IWYU pragma: keep
40
#include "common/config.h"
41
#include "common/consts.h"
42
#include "common/exception.h"
43
#include "common/logging.h"
44
#include "common/metrics/doris_metrics.h"
45
#include "common/object_pool.h"
46
#include "common/status.h"
47
#include "core/assert_cast.h"
48
#include "core/block/column_with_type_and_name.h"
49
#include "core/column/column.h"
50
#include "core/column/column_const.h"
51
#include "core/column/column_nothing.h"
52
#include "core/column/column_nullable.h"
53
#include "core/column/column_string.h"
54
#include "core/column/column_variant.h"
55
#include "core/column/column_vector.h"
56
#include "core/data_type/data_type.h"
57
#include "core/data_type/data_type_factory.hpp"
58
#include "core/data_type/data_type_number.h"
59
#include "core/data_type/define_primitive_type.h"
60
#include "core/field.h"
61
#include "core/string_ref.h"
62
#include "core/typeid_cast.h"
63
#include "core/types.h"
64
#include "exprs/expr_zonemap_filter.h"
65
#include "exprs/function/array/function_array_index.h"
66
#include "exprs/runtime_filter_expr.h"
67
#include "exprs/vexpr.h"
68
#include "exprs/vexpr_context.h"
69
#include "exprs/virtual_slot_ref.h"
70
#include "exprs/vliteral.h"
71
#include "exprs/vslot_ref.h"
72
#include "io/cache/cached_remote_file_reader.h"
73
#include "io/fs/file_reader.h"
74
#include "io/io_common.h"
75
#include "runtime/query_context.h"
76
#include "runtime/runtime_predicate.h"
77
#include "runtime/runtime_state.h"
78
#include "runtime/thread_context.h"
79
#include "service/backend_options.h"
80
#include "storage/binlog.h"
81
#include "storage/compaction/collection_similarity.h"
82
#include "storage/id_manager.h"
83
#include "storage/index/ann/ann_index.h"
84
#include "storage/index/ann/ann_index_iterator.h"
85
#include "storage/index/ann/ann_index_reader.h"
86
#include "storage/index/ann/ann_topn_runtime.h"
87
#include "storage/index/index_file_reader.h"
88
#include "storage/index/index_iterator.h"
89
#include "storage/index/index_query_context.h"
90
#include "storage/index/index_reader_helper.h"
91
#include "storage/index/indexed_column_reader.h"
92
#include "storage/index/inverted/inverted_index_reader.h"
93
#include "storage/index/ordinal_page_index.h"
94
#include "storage/index/primary_key_index.h"
95
#include "storage/index/short_key_index.h"
96
#include "storage/index/zone_map/zone_map_index.h"
97
#include "storage/index/zone_map/zonemap_eval_context.h"
98
#include "storage/iterators.h"
99
#include "storage/olap_common.h"
100
#include "storage/predicate/bloom_filter_predicate.h"
101
#include "storage/predicate/column_predicate.h"
102
#include "storage/predicate/like_column_predicate.h"
103
#include "storage/schema.h"
104
#include "storage/segment/column_reader.h"
105
#include "storage/segment/column_reader_cache.h"
106
#include "storage/segment/condition_cache.h"
107
#include "storage/segment/row_ranges.h"
108
#include "storage/segment/segment.h"
109
#include "storage/segment/segment_prefetcher.h"
110
#include "storage/segment/variant/variant_column_reader.h"
111
#include "storage/segment/virtual_column_iterator.h"
112
#include "storage/tablet/tablet_schema.h"
113
#include "storage/types.h"
114
#include "storage/utils.h"
115
#include "util/concurrency_stats.h"
116
#include "util/defer_op.h"
117
#include "util/simd/bits.h"
118
119
namespace doris {
120
using namespace ErrorCode;
121
namespace segment_v2 {
122
123
class ScopedColumnIteratorReadPhase {
124
public:
125
    ScopedColumnIteratorReadPhase(ColumnIterator* column_iter, ColumnIterator::ReadPhase mode)
126
37.1k
            : _column_iter(column_iter) {
127
37.1k
        DORIS_CHECK(_column_iter != nullptr);
128
37.1k
        _column_iter->set_read_phase(mode);
129
37.1k
    }
130
131
    ScopedColumnIteratorReadPhase(const ScopedColumnIteratorReadPhase&) = delete;
132
    ScopedColumnIteratorReadPhase& operator=(const ScopedColumnIteratorReadPhase&) = delete;
133
134
37.1k
    ~ScopedColumnIteratorReadPhase() {
135
        // ReadPhase is a per-read phase knob. SegmentIterator only needs a
136
        // temporary PREDICATE/LAZY mode while reading one column in one phase; it
137
        // must be restored before the next column or later normal reads reuse the
138
        // same ColumnIterator. Keep the restoration in one scoped helper instead
139
        // of open-coding the same Defer block at every call site.
140
37.1k
        _column_iter->set_read_phase(ColumnIterator::ReadPhase::NORMAL);
141
37.1k
    }
142
143
private:
144
    ColumnIterator* _column_iter = nullptr;
145
};
146
147
4.40k
SegmentIterator::~SegmentIterator() = default;
148
149
4.39k
void SegmentIterator::_init_row_bitmap_by_condition_cache() {
150
    // Only dispose need column predicate and expr cal in condition cache
151
4.39k
    if (!_col_predicates.empty() || !_common_expr_ctxs_push_down.empty()) {
152
92
        if (_opts.condition_cache_digest) {
153
0
            auto* condition_cache = ConditionCache::instance();
154
0
            ConditionCache::CacheKey cache_key(_opts.rowset_id, _segment->id(),
155
0
                                               _opts.condition_cache_digest);
156
157
            // Increment search count when digest != 0
158
0
            DorisMetrics::instance()->condition_cache_search_count->increment(1);
159
160
0
            ConditionCacheHandle handle;
161
0
            _find_condition_cache = condition_cache->lookup(cache_key, &handle);
162
163
            // Increment hit count if cache lookup is successful
164
0
            if (_find_condition_cache) {
165
0
                DorisMetrics::instance()->condition_cache_hit_count->increment(1);
166
0
                if (_opts.runtime_state) {
167
0
                    VLOG_DEBUG << "Condition cache hit, query id: "
168
0
                               << print_id(_opts.runtime_state->query_id())
169
0
                               << ", segment id: " << _segment->id()
170
0
                               << ", cache digest: " << _opts.condition_cache_digest
171
0
                               << ", rowset id: " << _opts.rowset_id.to_string();
172
0
                }
173
0
            }
174
175
0
            auto num_rows = _segment->num_rows();
176
0
            if (_find_condition_cache) {
177
0
                const auto& filter_result = *(handle.get_filter_result());
178
0
                int64_t filtered_blocks = 0;
179
0
                for (int i = 0; i < filter_result.size(); i++) {
180
0
                    if (!filter_result[i]) {
181
0
                        _row_bitmap.removeRange(
182
0
                                i * CONDITION_CACHE_OFFSET,
183
0
                                i * CONDITION_CACHE_OFFSET + CONDITION_CACHE_OFFSET);
184
0
                        filtered_blocks++;
185
0
                    }
186
0
                }
187
                // Record condition_cache hit segment number
188
0
                _opts.stats->condition_cache_hit_seg_nums++;
189
                // Record rows filtered by condition cache hit
190
0
                _opts.stats->condition_cache_filtered_rows +=
191
0
                        filtered_blocks * SegmentIterator::CONDITION_CACHE_OFFSET;
192
0
            } else {
193
0
                _condition_cache = std::make_shared<std::vector<bool>>(
194
0
                        num_rows / CONDITION_CACHE_OFFSET + 1, false);
195
0
            }
196
0
        }
197
4.30k
    } else {
198
4.30k
        _opts.condition_cache_digest = 0;
199
4.30k
    }
200
4.39k
}
201
202
// A fast range iterator for roaring bitmap. Output ranges use closed-open form, like [from, to).
203
// Example:
204
//   input bitmap:  [0 1 4 5 6 7 10 15 16 17 18 19]
205
//   output ranges: [0,2), [4,8), [10,11), [15,20) (when max_range_size=10)
206
//   output ranges: [0,2), [4,7), [7,8), [10,11), [15,18), [18,20) (when max_range_size=3)
207
class SegmentIterator::BitmapRangeIterator {
208
public:
209
0
    BitmapRangeIterator() = default;
210
4.39k
    virtual ~BitmapRangeIterator() = default;
211
212
4.39k
    explicit BitmapRangeIterator(const roaring::Roaring& bitmap) {
213
4.39k
        roaring_init_iterator(&bitmap.roaring, &_iter);
214
4.39k
    }
215
216
0
    bool has_more_range() const { return !_eof; }
217
218
8.78k
    [[nodiscard]] static uint32_t get_batch_size() { return kBatchSize; }
219
220
    // read next range into [*from, *to) whose size <= max_range_size.
221
    // return false when there is no more range.
222
0
    virtual bool next_range(const uint32_t max_range_size, uint32_t* from, uint32_t* to) {
223
0
        if (_eof) {
224
0
            return false;
225
0
        }
226
227
0
        *from = _buf[_buf_pos];
228
0
        uint32_t range_size = 0;
229
0
        uint32_t expect_val = _buf[_buf_pos]; // this initial value just make first batch valid
230
231
        // if array is contiguous sequence then the following conditions need to be met :
232
        // a_0: x
233
        // a_1: x+1
234
        // a_2: x+2
235
        // ...
236
        // a_p: x+p
237
        // so we can just use (a_p-a_0)-p to check conditions
238
        // and should notice the previous batch needs to be continuous with the current batch
239
0
        while (!_eof && range_size + _buf_size - _buf_pos <= max_range_size &&
240
0
               expect_val == _buf[_buf_pos] &&
241
0
               _buf[_buf_size - 1] - _buf[_buf_pos] == _buf_size - 1 - _buf_pos) {
242
0
            range_size += _buf_size - _buf_pos;
243
0
            expect_val = _buf[_buf_size - 1] + 1;
244
0
            _read_next_batch();
245
0
        }
246
247
        // promise remain range not will reach next batch
248
0
        if (!_eof && range_size < max_range_size && expect_val == _buf[_buf_pos]) {
249
0
            do {
250
0
                _buf_pos++;
251
0
                range_size++;
252
0
            } while (range_size < max_range_size && _buf[_buf_pos] == _buf[_buf_pos - 1] + 1);
253
0
        }
254
0
        *to = *from + range_size;
255
0
        return true;
256
0
    }
257
258
    // read batch_size of rowids from roaring bitmap into buf array
259
18.0k
    virtual uint32_t read_batch_rowids(rowid_t* buf, uint32_t batch_size) {
260
18.0k
        return roaring::api::roaring_read_uint32_iterator(&_iter, buf, batch_size);
261
18.0k
    }
262
263
private:
264
0
    void _read_next_batch() {
265
0
        _buf_pos = 0;
266
0
        _buf_size = roaring::api::roaring_read_uint32_iterator(&_iter, _buf, kBatchSize);
267
0
        _eof = (_buf_size == 0);
268
0
    }
269
270
    static const uint32_t kBatchSize = 256;
271
    roaring::api::roaring_uint32_iterator_t _iter;
272
    uint32_t _buf[kBatchSize];
273
    uint32_t _buf_pos = 0;
274
    uint32_t _buf_size = 0;
275
    bool _eof = false;
276
};
277
278
// A backward range iterator for roaring bitmap. Output ranges use closed-open form, like [from, to).
279
// Example:
280
//   input bitmap:  [0 1 4 5 6 7 10 15 16 17 18 19]
281
//   output ranges: , [15,20), [10,11), [4,8), [0,2) (when max_range_size=10)
282
//   output ranges: [17,20), [15,17), [10,11), [5,8), [4, 5), [0,2) (when max_range_size=3)
283
class SegmentIterator::BackwardBitmapRangeIterator : public SegmentIterator::BitmapRangeIterator {
284
public:
285
0
    explicit BackwardBitmapRangeIterator(const roaring::Roaring& bitmap) {
286
0
        roaring_init_iterator_last(&bitmap.roaring, &_riter);
287
0
        _rowid_count = cast_set<uint32_t>(roaring_bitmap_get_cardinality(&bitmap.roaring));
288
0
        _rowid_left = _rowid_count;
289
0
    }
290
291
0
    bool has_more_range() const { return !_riter.has_value; }
292
293
    // read next range into [*from, *to) whose size <= max_range_size.
294
    // return false when there is no more range.
295
0
    bool next_range(const uint32_t max_range_size, uint32_t* from, uint32_t* to) override {
296
0
        if (!_riter.has_value) {
297
0
            return false;
298
0
        }
299
300
0
        uint32_t range_size = 0;
301
0
        *to = _riter.current_value + 1;
302
303
0
        do {
304
0
            *from = _riter.current_value;
305
0
            range_size++;
306
0
            roaring_previous_uint32_iterator(&_riter);
307
0
        } while (range_size < max_range_size && _riter.has_value &&
308
0
                 _riter.current_value + 1 == *from);
309
310
0
        return true;
311
0
    }
312
    /**
313
     * Reads a batch of row IDs from a roaring bitmap, starting from the end and moving backwards.
314
     * This function retrieves the last `batch_size` row IDs from the bitmap and stores them in the provided buffer.
315
     * It updates the internal state to track how many row IDs are left to read in subsequent calls.
316
     *
317
     * The row IDs are read in reverse order, but stored in the buffer maintaining their original order in the bitmap.
318
     *
319
     * Example:
320
     *   input bitmap: [0 1 4 5 6 7 10 15 16 17 18 19]
321
     *   If the bitmap has 12 elements and batch_size is set to 5, the function will first read [15, 16, 17, 18, 19]
322
     *   into the buffer, leaving 7 elements left. In the next call with batch_size 5, it will read [4, 5, 6, 7, 10].
323
     *
324
     */
325
0
    uint32_t read_batch_rowids(rowid_t* buf, uint32_t batch_size) override {
326
0
        if (!_riter.has_value || _rowid_left == 0) {
327
0
            return 0;
328
0
        }
329
330
0
        if (_rowid_count <= batch_size) {
331
0
            roaring_bitmap_to_uint32_array(_riter.parent,
332
0
                                           buf); // Fill 'buf' with '_rowid_count' elements.
333
0
            uint32_t num_read = _rowid_left;     // Save the number of row IDs read.
334
0
            _rowid_left = 0;                     // No row IDs left after this operation.
335
0
            return num_read;                     // Return the number of row IDs read.
336
0
        }
337
338
0
        uint32_t read_size = std::min(batch_size, _rowid_left);
339
0
        uint32_t num_read = 0; // Counter for the number of row IDs read.
340
341
        // Read row IDs into the buffer in reverse order.
342
0
        while (num_read < read_size && _riter.has_value) {
343
0
            buf[read_size - num_read - 1] = _riter.current_value;
344
0
            num_read++;
345
0
            _rowid_left--; // Decrement the count of remaining row IDs.
346
0
            roaring_previous_uint32_iterator(&_riter);
347
0
        }
348
349
        // Return the actual number of row IDs read.
350
0
        return num_read;
351
0
    }
352
353
private:
354
    roaring::api::roaring_uint32_iterator_t _riter;
355
    uint32_t _rowid_count;
356
    uint32_t _rowid_left;
357
};
358
359
SegmentIterator::SegmentIterator(std::shared_ptr<Segment> segment, SchemaSPtr schema)
360
4.40k
        : _segment(std::move(segment)),
361
4.40k
          _schema(schema),
362
4.40k
          _column_iterators(_schema->num_columns()),
363
4.40k
          _index_iterators(_schema->num_columns()),
364
4.40k
          _cur_rowid(0),
365
4.40k
          _lazy_materialization_read(false),
366
4.40k
          _lazy_inited(false),
367
4.40k
          _inited(false),
368
4.40k
          _pool(new ObjectPool) {}
369
370
8.60k
Status SegmentIterator::init(const StorageReadOptions& opts) {
371
8.60k
    auto status = _init_impl(opts);
372
8.60k
    if (!status.ok()) {
373
0
        _segment->update_healthy_status(status);
374
0
    }
375
8.60k
    return status;
376
8.60k
}
377
378
4.39k
std::unique_ptr<AdaptiveBlockSizePredictor> SegmentIterator::_make_block_size_predictor() const {
379
4.39k
    if (!config::enable_adaptive_batch_size || _opts.preferred_block_size_bytes == 0) {
380
0
        return nullptr;
381
0
    }
382
383
    // Collect per-column raw byte metadata from the segment footer for the columns
384
    // this iterator will actually output (defined by _schema, which is built from
385
    // _opts.return_columns).
386
4.39k
    uint32_t seg_rows = _segment->num_rows();
387
4.39k
    uint64_t total_raw_bytes = 0;
388
4.39k
    double metadata_hint_bytes_per_row = 0.0;
389
4.39k
    if (seg_rows > 0) {
390
4.39k
        const auto& ts = _segment->tablet_schema();
391
4.39k
        if (ts) {
392
10.4k
            for (ColumnId cid : _schema->column_ids()) {
393
10.4k
                if (static_cast<size_t>(cid) < ts->num_columns()) {
394
10.2k
                    int32_t uid = ts->column(cid).unique_id();
395
10.2k
                    uint64_t raw_bytes = _segment->column_raw_data_bytes(uid);
396
10.2k
                    if (uid >= 0 && raw_bytes > 0) {
397
9.95k
                        total_raw_bytes += raw_bytes;
398
9.95k
                    }
399
10.2k
                }
400
10.4k
            }
401
4.39k
            metadata_hint_bytes_per_row = total_raw_bytes / static_cast<double>(seg_rows);
402
4.39k
        }
403
4.39k
    }
404
405
4.39k
    return std::make_unique<AdaptiveBlockSizePredictor>(
406
4.39k
            _opts.preferred_block_size_bytes, metadata_hint_bytes_per_row,
407
4.39k
            AdaptiveBlockSizePredictor::kDefaultProbeRows, _opts.block_row_max);
408
4.39k
}
409
410
8.60k
Status SegmentIterator::_init_impl(const StorageReadOptions& opts) {
411
    // get file handle from file descriptor of segment
412
8.60k
    if (_inited) {
413
4.20k
        return Status::OK();
414
4.20k
    }
415
4.39k
    _opts = opts;
416
4.39k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_timer_ns);
417
4.39k
    _inited = true;
418
4.39k
    _file_reader = _segment->_file_reader;
419
4.39k
    _col_predicates.clear();
420
421
4.39k
    for (const auto& predicate : opts.column_predicates) {
422
72
        if (!_segment->can_apply_predicate_safely(predicate->column_id(), *_schema,
423
72
                                                  _opts.target_cast_type_for_variants, _opts)) {
424
0
            continue;
425
0
        }
426
72
        _col_predicates.emplace_back(predicate);
427
72
    }
428
4.39k
    _tablet_id = opts.tablet_id;
429
    // Read options will not change, so that just resize here
430
4.39k
    _block_rowids.resize(_opts.block_row_max);
431
432
    // Adaptive batch size: snapshot the initial row limit and create predictor if enabled.
433
4.39k
    _initial_block_row_max = _opts.block_row_max;
434
4.39k
    _block_size_predictor = _make_block_size_predictor();
435
436
4.39k
    if (_schema->rowid_col_idx() > 0) {
437
0
        _record_rowids = true;
438
0
    }
439
440
4.39k
    _virtual_column_exprs = _opts.virtual_column_exprs;
441
4.39k
    _score_runtime = _opts.score_runtime;
442
4.39k
    _ann_topn_runtime = _opts.ann_topn_runtime;
443
444
4.39k
    _enable_prune_nested_column = _opts.io_ctx.reader_type == ReaderType::READER_QUERY &&
445
4.39k
                                  _opts.runtime_state &&
446
4.39k
                                  _opts.runtime_state->enable_prune_nested_column();
447
448
4.39k
    if (opts.output_columns != nullptr) {
449
2.67k
        _output_columns = *(opts.output_columns);
450
2.67k
    }
451
452
4.39k
    _storage_name_and_type.resize(_schema->columns().size());
453
4.39k
    auto storage_format = _opts.tablet_schema->get_inverted_index_storage_format();
454
33.1k
    for (int i = 0; i < _schema->columns().size(); ++i) {
455
28.7k
        const TabletColumn* col = _schema->column(i);
456
28.7k
        if (col) {
457
10.4k
            auto storage_type = _segment->get_data_type_of(*col, _opts);
458
10.4k
            if (storage_type == nullptr) {
459
0
                storage_type =
460
0
                        DataTypeFactory::instance().create_data_type(*col, col->is_nullable());
461
0
            }
462
            // Currently, when writing a lucene index, the field of the document is column_name, and the column name is
463
            // bound to the index field. Since version 1.2, the data file storage has been changed from column_name to
464
            // column_unique_id, allowing the column name to be changed. Due to current limitations, previous inverted
465
            // index data cannot be used after Doris changes the column name. Column names also support Unicode
466
            // characters, which may cause other problems with indexing in non-ASCII characters.
467
            // After consideration, it was decided to change the field name from column_name to column_unique_id in
468
            // format V2, while format V1 continues to use column_name.
469
10.4k
            std::string field_name;
470
10.4k
            if (storage_format == InvertedIndexStorageFormatPB::V1) {
471
7.14k
                field_name = col->name();
472
7.14k
            } else {
473
3.30k
                if (col->is_extracted_column()) {
474
                    // variant sub col
475
                    // field_name format: parent_unique_id.sub_col_name
476
264
                    field_name = std::to_string(col->parent_unique_id()) + "." + col->name();
477
3.04k
                } else {
478
3.04k
                    field_name = std::to_string(col->unique_id());
479
3.04k
                }
480
3.30k
            }
481
10.4k
            _storage_name_and_type[i] = std::make_pair(field_name, storage_type);
482
10.4k
            if (int32_t uid =
483
10.4k
                        col->is_extracted_column() ? col->parent_unique_id() : col->unique_id();
484
10.4k
                !_variant_sparse_column_cache.contains(uid)) {
485
10.2k
                DCHECK(uid >= 0);
486
10.2k
                _variant_sparse_column_cache.emplace(uid,
487
10.2k
                                                     std::make_unique<PathToBinaryColumnCache>());
488
10.2k
            }
489
10.4k
        }
490
28.7k
    }
491
492
4.39k
    RETURN_IF_ERROR(init_iterators());
493
494
4.39k
    RETURN_IF_ERROR(_construct_compound_expr_context());
495
4.39k
    VLOG_DEBUG << fmt::format(
496
0
            "Segment iterator init, virtual_column_exprs size: {}, common_expr_pushdown size: {}",
497
0
            _opts.virtual_column_exprs.size(), _common_expr_ctxs_push_down.size());
498
4.39k
    _initialize_predicate_results();
499
4.39k
    return Status::OK();
500
4.39k
}
501
502
4.39k
void SegmentIterator::_initialize_predicate_results() {
503
    // Initialize from _col_predicates
504
4.39k
    for (auto pred : _col_predicates) {
505
72
        int cid = pred->column_id();
506
72
        _column_predicate_index_exec_status[cid][pred] = false;
507
72
    }
508
509
4.39k
    _calculate_common_expr_index_exec_status();
510
4.39k
}
511
512
4.39k
Status SegmentIterator::init_iterators() {
513
4.39k
    RETURN_IF_ERROR(_init_return_column_iterators());
514
4.39k
    RETURN_IF_ERROR(_init_index_iterators());
515
4.39k
    return Status::OK();
516
4.39k
}
517
518
18.0k
Status SegmentIterator::_lazy_init(Block* block) {
519
18.0k
    if (_lazy_inited) {
520
13.6k
        return Status::OK();
521
13.6k
    }
522
4.39k
    SCOPED_RAW_TIMER(&_opts.stats->block_init_ns);
523
4.39k
    DorisMetrics::instance()->segment_read_total->increment(1);
524
4.39k
    _row_bitmap.addRange(0, _segment->num_rows());
525
4.39k
    _init_row_bitmap_by_condition_cache();
526
527
    // z-order can not use prefix index
528
4.39k
    if (_segment->_tablet_schema->sort_type() != SortType::ZORDER &&
529
4.39k
        _segment->_tablet_schema->cluster_key_uids().empty()) {
530
4.39k
        RETURN_IF_ERROR(_get_row_ranges_by_keys());
531
4.39k
    }
532
4.39k
    RETURN_IF_ERROR(_get_row_ranges_by_column_conditions());
533
4.39k
    RETURN_IF_ERROR(_vec_init_lazy_materialization());
534
    // Remove rows that have been marked deleted
535
4.39k
    if (_opts.delete_bitmap.count(segment_id()) > 0 &&
536
4.39k
        _opts.delete_bitmap.at(segment_id()) != nullptr) {
537
25
        size_t pre_size = _row_bitmap.cardinality();
538
25
        _row_bitmap -= *(_opts.delete_bitmap.at(segment_id()));
539
25
        _opts.stats->rows_del_by_bitmap += (pre_size - _row_bitmap.cardinality());
540
25
        VLOG_DEBUG << "read on segment: " << segment_id() << ", delete bitmap cardinality: "
541
0
                   << _opts.delete_bitmap.at(segment_id())->cardinality() << ", "
542
0
                   << _opts.stats->rows_del_by_bitmap << " rows deleted by bitmap";
543
25
    }
544
545
4.39k
    if (!_opts.row_ranges.is_empty()) {
546
0
        _row_bitmap &= RowRanges::ranges_to_roaring(_opts.row_ranges);
547
0
    }
548
549
4.39k
    _prepare_score_column_materialization();
550
551
4.39k
    RETURN_IF_ERROR(_apply_ann_topn_predicate());
552
553
4.39k
    if (_opts.read_orderby_key_reverse) {
554
0
        _range_iter.reset(new BackwardBitmapRangeIterator(_row_bitmap));
555
4.39k
    } else {
556
4.39k
        _range_iter.reset(new BitmapRangeIterator(_row_bitmap));
557
4.39k
    }
558
559
    // Reserve columns for _initial_block_row_max (the original max before any adaptive
560
    // prediction) because the predictor may increase block_row_max on subsequent batches
561
    // up to this ceiling. Using the current (possibly reduced) _opts.block_row_max would
562
    // cause heap-buffer-overflow if a later prediction is larger.
563
4.39k
    auto nrows_reserve_limit =
564
4.39k
            std::min(_row_bitmap.cardinality(), uint64_t(_initial_block_row_max));
565
4.39k
    if (_lazy_materialization_read || _opts.record_rowids || _is_need_expr_eval) {
566
921
        _block_rowids.resize(_initial_block_row_max);
567
921
    }
568
4.39k
    _current_return_columns.resize(_schema->columns().size());
569
570
14.8k
    for (size_t i = 0; i < _schema->column_ids().size(); i++) {
571
10.4k
        ColumnId cid = _schema->column_ids()[i];
572
10.4k
        const auto* column_desc = _schema->column(cid);
573
10.4k
        if (_is_pred_column[cid]) {
574
486
            auto storage_column_type = _storage_name_and_type[cid].second;
575
486
            RETURN_IF_CATCH_EXCEPTION(
576
                    // Here, cid will not go out of bounds
577
                    // because the size of _current_return_columns equals _schema->tablet_columns().size()
578
486
                    _current_return_columns[cid] = Schema::get_predicate_column_ptr(
579
486
                            storage_column_type, _opts.io_ctx.reader_type));
580
486
            _current_return_columns[cid]->set_rowset_segment_id(
581
486
                    {_segment->rowset_id(), _segment->id()});
582
486
            _current_return_columns[cid]->reserve(nrows_reserve_limit);
583
9.96k
        } else if (i >= block->columns()) {
584
            // This column needs to be scanned, but doesn't need to be returned upward. (delete sign)
585
            // if i >= block->columns means the column and not the pred_column means `column i` is
586
            // a delete condition column. but the column is not effective in the segment. so we just
587
            // create a column to hold the data.
588
            // a. origin data -> b. delete condition -> c. new load data
589
            // the segment of c do not effective delete condition, but it still need read the column
590
            // to match the schema.
591
            // TODO: skip read the not effective delete column to speed up segment read.
592
0
            _current_return_columns[cid] = Schema::get_data_type_ptr(*column_desc)->create_column();
593
0
            _current_return_columns[cid]->reserve(nrows_reserve_limit);
594
0
        }
595
10.4k
    }
596
597
    // Additional deleted filter condition will be materialized column be at the end of the block,
598
    // after _output_column_by_sel_idx  will be erase, we not need to filter it,
599
    // so erase it from _columns_to_filter in the first next_batch.
600
    // Eg:
601
    //      `delete from table where a = 10;`
602
    //      `select b from table;`
603
    // a column only effective in segment iterator, the block from query engine only contain the b column,
604
    // so no need to filter a column by expr.
605
4.39k
    for (auto it = _columns_to_filter.begin(); it != _columns_to_filter.end();) {
606
6
        if (*it >= block->columns()) {
607
0
            it = _columns_to_filter.erase(it);
608
6
        } else {
609
6
            ++it;
610
6
        }
611
6
    }
612
613
4.39k
    _lazy_inited = true;
614
615
4.39k
    _init_segment_prefetchers();
616
617
4.39k
    return Status::OK();
618
4.39k
}
619
620
4.39k
void SegmentIterator::_init_segment_prefetchers() {
621
4.39k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_segment_prefetchers_timer_ns);
622
4.39k
    if (!config::is_cloud_mode()) {
623
4.39k
        return;
624
4.39k
    }
625
0
    static std::vector<ReaderType> supported_reader_types {
626
0
            ReaderType::READER_QUERY, ReaderType::READER_BASE_COMPACTION,
627
0
            ReaderType::READER_CUMULATIVE_COMPACTION, ReaderType::READER_FULL_COMPACTION};
628
0
    if (std::ranges::none_of(supported_reader_types,
629
0
                             [&](ReaderType t) { return _opts.io_ctx.reader_type == t; })) {
630
0
        return;
631
0
    }
632
    // Initialize segment prefetcher for predicate and non-predicate columns
633
0
    bool is_query = (_opts.io_ctx.reader_type == ReaderType::READER_QUERY);
634
0
    bool enable_prefetch = is_query ? config::enable_query_segment_file_cache_prefetch
635
0
                                    : config::enable_compaction_segment_file_cache_prefetch;
636
0
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
637
0
            "[verbose] SegmentIterator _init_segment_prefetchers, is_query={}, "
638
0
            "enable_prefetch={}, "
639
0
            "_row_bitmap.isEmpty()={}, row_bitmap.cardinality()={}, tablet={}, rowset={}, "
640
0
            "segment={}, predicate_column_ids={}, common_expr_column_ids={}",
641
0
            is_query, enable_prefetch, _row_bitmap.isEmpty(), _row_bitmap.cardinality(),
642
0
            _opts.tablet_id, _opts.rowset_id.to_string(), segment_id(),
643
0
            fmt::join(_predicate_column_ids, ","), fmt::join(_common_expr_column_ids, ","));
644
0
    if (enable_prefetch && !_row_bitmap.isEmpty()) {
645
0
        int window_size =
646
0
                1 + (is_query ? config::query_segment_file_cache_prefetch_block_size
647
0
                              : config::compaction_segment_file_cache_prefetch_block_size);
648
0
        LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
649
0
                "[verbose] SegmentIterator prefetch config: window_size={}", window_size);
650
0
        if (window_size > 0 &&
651
0
            !_column_iterators.empty()) { // ensure init_iterators has been called
652
0
            SegmentPrefetcherConfig prefetch_config(window_size,
653
0
                                                    config::file_cache_each_block_size);
654
0
            for (auto cid : _schema->column_ids()) {
655
0
                auto& column_iter = _column_iterators[cid];
656
0
                if (column_iter == nullptr) {
657
0
                    continue;
658
0
                }
659
0
                const auto* tablet_column = _schema->column(cid);
660
0
                SegmentPrefetchParams params {
661
0
                        .config = prefetch_config,
662
0
                        .read_options = _opts,
663
0
                };
664
0
                LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
665
0
                        "[verbose] SegmentIterator init_segment_prefetchers, "
666
0
                        "tablet={}, rowset={}, segment={}, column_id={}, col_name={}, type={}",
667
0
                        _opts.tablet_id, _opts.rowset_id.to_string(), segment_id(), cid,
668
0
                        tablet_column->name(), tablet_column->type());
669
0
                Status st = column_iter->init_prefetcher(params);
670
0
                if (!st.ok()) {
671
0
                    LOG_IF(WARNING, config::enable_segment_prefetch_verbose_log) << fmt::format(
672
0
                            "[verbose] failed to init prefetcher for column_id={}, "
673
0
                            "tablet={}, rowset={}, segment={}, error={}",
674
0
                            cid, _opts.tablet_id, _opts.rowset_id.to_string(), segment_id(),
675
0
                            st.to_string());
676
0
                }
677
0
            }
678
679
            // for compaction, it's guaranteed that all rows are read, so we can prefetch all data blocks
680
0
            PrefetcherInitMethod init_method = (is_query && _row_bitmap.cardinality() < num_rows())
681
0
                                                       ? PrefetcherInitMethod::FROM_ROWIDS
682
0
                                                       : PrefetcherInitMethod::ALL_DATA_BLOCKS;
683
0
            std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>> prefetchers;
684
0
            for (size_t idx = 0; idx < _column_iterators.size(); ++idx) {
685
0
                auto cid = cast_set<ColumnId>(idx);
686
0
                auto* column_iter = _column_iterators[cid].get();
687
0
                if (column_iter != nullptr) {
688
0
                    ScopedColumnIteratorReadPhase scoped_read_phase {
689
0
                            column_iter, _support_lazy_read_pruned_columns.contains(cid)
690
0
                                                 ? ColumnIterator::ReadPhase::PREDICATE
691
0
                                                 : ColumnIterator::ReadPhase::NORMAL};
692
0
                    column_iter->collect_prefetchers(prefetchers, init_method);
693
0
                }
694
0
            }
695
0
            for (auto& [method, prefetcher_vec] : prefetchers) {
696
0
                if (method == PrefetcherInitMethod::ALL_DATA_BLOCKS) {
697
0
                    for (auto* prefetcher : prefetcher_vec) {
698
0
                        prefetcher->build_all_data_blocks();
699
0
                    }
700
0
                } else if (method == PrefetcherInitMethod::FROM_ROWIDS && !prefetcher_vec.empty()) {
701
0
                    SegmentPrefetcher::build_blocks_by_rowids(_row_bitmap, prefetcher_vec);
702
0
                }
703
0
            }
704
0
        }
705
0
    }
706
0
}
707
708
4.39k
Status SegmentIterator::_get_row_ranges_by_keys() {
709
4.39k
    SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_keys_ns);
710
4.39k
    DorisMetrics::instance()->segment_row_total->increment(num_rows());
711
712
    // fast path for empty segment or empty key ranges
713
4.39k
    if (_row_bitmap.isEmpty() || _opts.key_ranges.empty()) {
714
4.39k
        return Status::OK();
715
4.39k
    }
716
717
    // Read & seek key columns is a waste of time when no key column in _schema
718
0
    if (std::none_of(_schema->columns().begin(), _schema->columns().end(),
719
0
                     [&](const TabletColumnPtr& col) {
720
0
                         return col &&
721
0
                                _opts.tablet_schema->column_by_uid(col->unique_id()).is_key();
722
0
                     })) {
723
0
        return Status::OK();
724
0
    }
725
726
0
    RowRanges result_ranges;
727
0
    for (auto& key_range : _opts.key_ranges) {
728
0
        rowid_t lower_rowid = 0;
729
0
        rowid_t upper_rowid = num_rows();
730
0
        RETURN_IF_ERROR(_prepare_seek(key_range));
731
0
        if (key_range.upper_key != nullptr) {
732
            // If client want to read upper_bound, the include_upper is true. So we
733
            // should get the first ordinal at which key is larger than upper_bound.
734
            // So we call _lookup_ordinal with include_upper's negate
735
0
            RETURN_IF_ERROR(_lookup_ordinal(*key_range.upper_key, !key_range.include_upper,
736
0
                                            num_rows(), &upper_rowid));
737
0
        }
738
0
        if (upper_rowid > 0 && key_range.lower_key != nullptr) {
739
0
            RETURN_IF_ERROR(_lookup_ordinal(*key_range.lower_key, key_range.include_lower,
740
0
                                            upper_rowid, &lower_rowid));
741
0
        }
742
0
        auto row_range = RowRanges::create_single(lower_rowid, upper_rowid);
743
0
        RowRanges::ranges_union(result_ranges, row_range, &result_ranges);
744
0
    }
745
0
    size_t pre_size = _row_bitmap.cardinality();
746
0
    _row_bitmap &= RowRanges::ranges_to_roaring(result_ranges);
747
0
    _opts.stats->rows_key_range_filtered += (pre_size - _row_bitmap.cardinality());
748
749
0
    return Status::OK();
750
0
}
751
752
// Set up environment for the following seek.
753
0
Status SegmentIterator::_prepare_seek(const StorageReadOptions::KeyRange& key_range) {
754
0
    std::vector<const TabletColumn*> key_columns;
755
0
    std::set<uint32_t> column_set;
756
0
    if (key_range.lower_key != nullptr) {
757
0
        for (auto cid : key_range.lower_key->schema()->column_ids()) {
758
0
            column_set.emplace(cid);
759
0
            key_columns.emplace_back(key_range.lower_key->column(cid));
760
0
        }
761
0
    }
762
0
    if (key_range.upper_key != nullptr) {
763
0
        for (auto cid : key_range.upper_key->schema()->column_ids()) {
764
0
            if (column_set.count(cid) == 0) {
765
0
                key_columns.emplace_back(key_range.upper_key->column(cid));
766
0
                column_set.emplace(cid);
767
0
            }
768
0
        }
769
0
    }
770
0
    if (!_seek_schema) {
771
0
        std::vector<TabletColumnPtr> cols;
772
0
        cols.reserve(key_columns.size());
773
0
        for (const TabletColumn* col : key_columns) {
774
0
            cols.emplace_back(std::make_shared<TabletColumn>(*col));
775
0
        }
776
0
        std::vector<uint32_t> column_ids(cols.size());
777
0
        std::iota(column_ids.begin(), column_ids.end(), 0);
778
0
        _seek_schema = std::make_unique<Schema>(cols, column_ids);
779
0
    }
780
    // todo(wb) need refactor here, when using pk to search, _seek_block is useless
781
0
    if (_seek_block.size() == 0) {
782
0
        _seek_block.resize(_seek_schema->num_column_ids());
783
0
        int i = 0;
784
0
        for (auto cid : _seek_schema->column_ids()) {
785
0
            auto column_desc = _seek_schema->column(cid);
786
0
            _seek_block[i] = Schema::get_data_type_ptr(*column_desc)->create_column();
787
0
            i++;
788
0
        }
789
0
    }
790
791
    // create used column iterator
792
0
    for (auto cid : _seek_schema->column_ids()) {
793
0
        if (_column_iterators[cid] == nullptr) {
794
            // TODO: Do we need this?
795
0
            if (_virtual_column_exprs.contains(cid)) {
796
0
                _column_iterators[cid] = std::make_unique<VirtualColumnIterator>();
797
0
                continue;
798
0
            }
799
800
0
            RETURN_IF_ERROR(_segment->new_column_iterator(_opts.tablet_schema->column(cid),
801
0
                                                          &_column_iterators[cid], &_opts,
802
0
                                                          &_variant_sparse_column_cache));
803
0
            ColumnIteratorOptions iter_opts {
804
0
                    .use_page_cache = _opts.use_page_cache,
805
0
                    .file_reader = _file_reader.get(),
806
0
                    .stats = _opts.stats,
807
0
                    .io_ctx = _opts.io_ctx,
808
0
            };
809
0
            RETURN_IF_ERROR(_column_iterators[cid]->init(iter_opts));
810
0
        }
811
0
    }
812
813
0
    return Status::OK();
814
0
}
815
816
4.39k
Status SegmentIterator::_get_row_ranges_by_column_conditions() {
817
4.39k
    SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_column_conditions_ns);
818
4.39k
    if (_row_bitmap.isEmpty()) {
819
0
        return Status::OK();
820
0
    }
821
822
4.39k
    {
823
4.39k
        if (_opts.runtime_state &&
824
4.39k
            _opts.runtime_state->query_options().enable_inverted_index_query &&
825
4.39k
            (has_index_in_iterators() || !_common_expr_ctxs_push_down.empty())) {
826
75
            SCOPED_RAW_TIMER(&_opts.stats->inverted_index_filter_timer);
827
75
            size_t input_rows = _row_bitmap.cardinality();
828
            // Only apply column-level inverted index if we have iterators
829
75
            if (has_index_in_iterators()) {
830
71
                RETURN_IF_ERROR(_apply_inverted_index());
831
71
            }
832
            // Always apply expr-level index (e.g., search expressions) if we have common_expr_pushdown
833
            // This allows search expressions with variant subcolumns to be evaluated even when
834
            // the segment doesn't have all subcolumns
835
75
            RETURN_IF_ERROR(_apply_index_expr());
836
75
            for (auto it = _common_expr_ctxs_push_down.begin();
837
93
                 it != _common_expr_ctxs_push_down.end();) {
838
18
                if ((*it)->all_expr_inverted_index_evaluated()) {
839
14
                    const auto* result = (*it)->get_index_context()->get_index_result_for_expr(
840
14
                            (*it)->root().get());
841
14
                    if (result != nullptr) {
842
14
                        _row_bitmap &= *result->get_data_bitmap();
843
14
                        it = _common_expr_ctxs_push_down.erase(it);
844
14
                    }
845
14
                } else {
846
4
                    ++it;
847
4
                }
848
18
            }
849
75
            _opts.condition_cache_digest =
850
75
                    _common_expr_ctxs_push_down.empty() ? 0 : _opts.condition_cache_digest;
851
75
            _opts.stats->rows_inverted_index_filtered += (input_rows - _row_bitmap.cardinality());
852
160
            for (auto cid : _schema->column_ids()) {
853
160
                bool result_true = _check_all_conditions_passed_inverted_index_for_column(cid);
854
160
                if (result_true) {
855
67
                    _need_read_data_indices[cid] = false;
856
67
                }
857
160
            }
858
75
        }
859
4.39k
    }
860
861
4.39k
    DBUG_EXECUTE_IF("segment_iterator.inverted_index.filtered_rows", {
862
4.39k
        LOG(INFO) << "Debug Point: segment_iterator.inverted_index.filtered_rows: "
863
4.39k
                  << _opts.stats->rows_inverted_index_filtered;
864
4.39k
        auto filtered_rows = DebugPoints::instance()->get_debug_param_or_default<int32_t>(
865
4.39k
                "segment_iterator.inverted_index.filtered_rows", "filtered_rows", -1);
866
4.39k
        if (filtered_rows != _opts.stats->rows_inverted_index_filtered) {
867
4.39k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
868
4.39k
                    "filtered_rows: {} not equal to expected: {}",
869
4.39k
                    _opts.stats->rows_inverted_index_filtered, filtered_rows);
870
4.39k
        }
871
4.39k
    })
872
873
4.39k
    DBUG_EXECUTE_IF("segment_iterator.apply_inverted_index", {
874
4.39k
        LOG(INFO) << "Debug Point: segment_iterator.apply_inverted_index";
875
4.39k
        if (!_common_expr_ctxs_push_down.empty() || !_col_predicates.empty()) {
876
4.39k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
877
4.39k
                    "it is failed to apply inverted index, common_expr_ctxs_push_down: {}, "
878
4.39k
                    "col_predicates: {}",
879
4.39k
                    _common_expr_ctxs_push_down.size(), _col_predicates.size());
880
4.39k
        }
881
4.39k
    })
882
883
4.39k
    if (!_row_bitmap.isEmpty() &&
884
4.39k
        (!_opts.topn_filter_source_node_ids.empty() || !_opts.col_id_to_predicates.empty() ||
885
4.39k
         _opts.delete_condition_predicates->num_of_column_predicate() > 0 ||
886
4.39k
         !_common_expr_ctxs_push_down.empty())) {
887
545
        RowRanges condition_row_ranges = RowRanges::create_single(_segment->num_rows());
888
545
        RETURN_IF_ERROR(_get_row_ranges_from_conditions(&condition_row_ranges));
889
545
        size_t pre_size = _row_bitmap.cardinality();
890
545
        _row_bitmap &= RowRanges::ranges_to_roaring(condition_row_ranges);
891
545
        _opts.stats->rows_conditions_filtered += (pre_size - _row_bitmap.cardinality());
892
545
    }
893
894
4.39k
    DBUG_EXECUTE_IF("bloom_filter_must_filter_data", {
895
4.39k
        if (_opts.stats->rows_bf_filtered == 0) {
896
4.39k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
897
4.39k
                    "Bloom filter did not filter the data.");
898
4.39k
        }
899
4.39k
    })
900
901
    // TODO(hkp): calculate filter rate to decide whether to
902
    // use zone map/bloom filter/secondary index or not.
903
4.39k
    return Status::OK();
904
4.39k
}
905
906
0
bool SegmentIterator::_column_has_ann_index(int32_t cid) {
907
0
    bool has_ann_index = _index_iterators[cid] != nullptr &&
908
0
                         _index_iterators[cid]->get_reader(AnnIndexReaderType::ANN);
909
910
0
    return has_ann_index;
911
0
}
912
913
4.39k
Status SegmentIterator::_apply_ann_topn_predicate() {
914
4.39k
    if (_ann_topn_runtime == nullptr) {
915
4.39k
        return Status::OK();
916
4.39k
    }
917
918
0
    VLOG_DEBUG << fmt::format("Try apply ann topn: {}", _ann_topn_runtime->debug_string());
919
0
    size_t src_col_idx = _ann_topn_runtime->get_src_column_idx();
920
    // AnnTopNRuntime keeps VSlotRef::column_id(), which is the scan schema ordinal.
921
0
    ColumnId src_cid = _schema->column_id(src_col_idx);
922
0
    IndexIterator* ann_index_iterator = _index_iterators[src_cid].get();
923
0
    bool has_ann_index = _column_has_ann_index(src_cid);
924
0
    bool has_common_expr_push_down = !_common_expr_ctxs_push_down.empty();
925
0
    bool has_column_predicate = std::any_of(_is_pred_column.begin(), _is_pred_column.end(),
926
0
                                            [](bool is_pred) { return is_pred; });
927
0
    if (!has_ann_index || has_common_expr_push_down || has_column_predicate) {
928
0
        VLOG_DEBUG << fmt::format(
929
0
                "Ann topn can not be evaluated by ann index, has_ann_index: {}, "
930
0
                "has_common_expr_push_down: {}, has_column_predicate: {}",
931
0
                has_ann_index, has_common_expr_push_down, has_column_predicate);
932
        // Disable index-only scan on ann indexed column.
933
0
        _need_read_data_indices[src_cid] = true;
934
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
935
0
        return Status::OK();
936
0
    }
937
938
    // Process asc & desc according to the type of metric
939
0
    auto index_reader = ann_index_iterator->get_reader(AnnIndexReaderType::ANN);
940
0
    auto ann_index_reader = dynamic_cast<AnnIndexReader*>(index_reader.get());
941
0
    DCHECK(ann_index_reader != nullptr);
942
0
    if (ann_index_reader->get_metric_type() == AnnIndexMetric::IP) {
943
0
        if (_ann_topn_runtime->is_asc()) {
944
0
            VLOG_DEBUG << fmt::format(
945
0
                    "Asc topn for inner product can not be evaluated by ann index");
946
            // Disable index-only scan on ann indexed column.
947
0
            _need_read_data_indices[src_cid] = true;
948
0
            _opts.stats->ann_fall_back_brute_force_cnt += 1;
949
0
            return Status::OK();
950
0
        }
951
0
    } else {
952
0
        if (!_ann_topn_runtime->is_asc()) {
953
0
            VLOG_DEBUG << fmt::format("Desc topn for l2/cosine can not be evaluated by ann index");
954
            // Disable index-only scan on ann indexed column.
955
0
            _need_read_data_indices[src_cid] = true;
956
0
            _opts.stats->ann_fall_back_brute_force_cnt += 1;
957
0
            return Status::OK();
958
0
        }
959
0
    }
960
961
0
    if (ann_index_reader->get_metric_type() != _ann_topn_runtime->get_metric_type()) {
962
0
        VLOG_DEBUG << fmt::format(
963
0
                "Ann topn metric type {} not match index metric type {}, can not be evaluated "
964
0
                "by "
965
0
                "ann index",
966
0
                metric_to_string(_ann_topn_runtime->get_metric_type()),
967
0
                metric_to_string(ann_index_reader->get_metric_type()));
968
        // Disable index-only scan on ann indexed column.
969
0
        _need_read_data_indices[src_cid] = true;
970
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
971
0
        return Status::OK();
972
0
    }
973
974
0
    size_t pre_size = _row_bitmap.cardinality();
975
0
    size_t rows_of_segment = _segment->num_rows();
976
0
    const auto& user_params = _ann_topn_runtime->user_params();
977
0
    if (user_params.should_fallback_ann_index_by_small_candidate(pre_size, rows_of_segment)) {
978
0
        VLOG_DEBUG << fmt::format(
979
0
                "Ann topn predicate input rows {} reach small candidate threshold, "
980
0
                "rows_of_segment: {}, absolute_threshold: {}, percent_threshold: {}, "
981
0
                "will not use ann index to filter",
982
0
                pre_size, rows_of_segment, user_params.ann_index_candidate_rows_threshold,
983
0
                user_params.ann_index_candidate_rows_percent_threshold);
984
        // Disable index-only scan on ann indexed column.
985
0
        _need_read_data_indices[src_cid] = true;
986
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
987
0
        _opts.stats->ann_topn_fallback_by_small_candidate_cnt += 1;
988
0
        _opts.stats->ann_topn_fallback_small_candidate_rows += pre_size;
989
0
        return Status::OK();
990
0
    }
991
0
    IColumn::MutablePtr result_column;
992
0
    std::shared_ptr<std::vector<uint64_t>> result_row_ids;
993
0
    segment_v2::AnnIndexStats ann_index_stats;
994
995
    // Try to load ANN index before search
996
0
    auto ann_index_iterator_casted =
997
0
            dynamic_cast<segment_v2::AnnIndexIterator*>(ann_index_iterator);
998
0
    if (ann_index_iterator_casted == nullptr) {
999
0
        VLOG_DEBUG << "Failed to cast index iterator to AnnIndexIterator, fallback to brute force";
1000
0
        _need_read_data_indices[src_cid] = true;
1001
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
1002
0
        return Status::OK();
1003
0
    }
1004
1005
    // Track load index timing
1006
0
    {
1007
0
        SCOPED_TIMER(&(ann_index_stats.load_index_costs_ns));
1008
0
        if (!ann_index_iterator_casted->try_load_index()) {
1009
0
            VLOG_DEBUG << "Failed to load ANN index, fallback to brute force search";
1010
0
            _need_read_data_indices[src_cid] = true;
1011
0
            _opts.stats->ann_fall_back_brute_force_cnt += 1;
1012
0
            return Status::OK();
1013
0
        }
1014
0
        double load_costs_ms =
1015
0
                static_cast<double>(ann_index_stats.load_index_costs_ns.value()) / 1000000.0;
1016
0
        DorisMetrics::instance()->ann_index_load_costs_ms->increment(
1017
0
                static_cast<int64_t>(load_costs_ms));
1018
0
    }
1019
1020
0
    bool enable_ann_index_result_cache =
1021
0
            !_opts.runtime_state ||
1022
0
            !_opts.runtime_state->query_options().__isset.enable_ann_index_result_cache ||
1023
0
            _opts.runtime_state->query_options().enable_ann_index_result_cache;
1024
0
    RETURN_IF_ERROR(_ann_topn_runtime->evaluate_vector_ann_search(
1025
0
            ann_index_iterator_casted, &_row_bitmap, rows_of_segment, enable_ann_index_result_cache,
1026
0
            result_column, result_row_ids, ann_index_stats));
1027
1028
0
    VLOG_DEBUG << fmt::format("Ann topn filtered {} - {} = {} rows", pre_size,
1029
0
                              _row_bitmap.cardinality(), pre_size - _row_bitmap.cardinality());
1030
1031
0
    int64_t rows_filterd = pre_size - _row_bitmap.cardinality();
1032
0
    _opts.stats->rows_ann_index_topn_filtered += rows_filterd;
1033
0
    _opts.stats->ann_index_load_ns += ann_index_stats.load_index_costs_ns.value();
1034
0
    _opts.stats->ann_topn_search_ns += ann_index_stats.search_costs_ns.value();
1035
0
    _opts.stats->ann_ivf_on_disk_load_ns += ann_index_stats.ivf_on_disk_load_costs_ns.value();
1036
0
    _opts.stats->ann_ivf_on_disk_cache_hit_cnt += ann_index_stats.ivf_on_disk_cache_hit_cnt.value();
1037
0
    _opts.stats->ann_ivf_on_disk_cache_miss_cnt +=
1038
0
            ann_index_stats.ivf_on_disk_cache_miss_cnt.value();
1039
0
    _opts.stats->ann_index_topn_engine_search_ns += ann_index_stats.engine_search_ns.value();
1040
0
    _opts.stats->ann_index_topn_result_process_ns +=
1041
0
            ann_index_stats.result_process_costs_ns.value();
1042
0
    _opts.stats->ann_index_topn_engine_convert_ns += ann_index_stats.engine_convert_ns.value();
1043
0
    _opts.stats->ann_index_topn_engine_prepare_ns += ann_index_stats.engine_prepare_ns.value();
1044
0
    _opts.stats->ann_index_topn_search_cnt += 1;
1045
0
    _opts.stats->ann_index_cache_hits += ann_index_stats.topn_cache_hits.value();
1046
0
    const size_t dst_col_idx = _ann_topn_runtime->get_dest_column_idx();
1047
0
    ColumnIterator* column_iter = _column_iterators[_schema->column_id(dst_col_idx)].get();
1048
0
    DCHECK(column_iter != nullptr);
1049
0
    VirtualColumnIterator* virtual_column_iter = dynamic_cast<VirtualColumnIterator*>(column_iter);
1050
0
    DCHECK(virtual_column_iter != nullptr);
1051
0
    VLOG_DEBUG << fmt::format(
1052
0
            "Virtual column iterator, column_idx {}, is materialized with {} rows", dst_col_idx,
1053
0
            result_row_ids->size());
1054
    // reference count of result_column should be 1, so move will not issue any data copy.
1055
0
    virtual_column_iter->prepare_materialization(std::move(result_column), result_row_ids);
1056
1057
0
    _need_read_data_indices[src_cid] = false;
1058
0
    VLOG_DEBUG << fmt::format(
1059
0
            "Enable ANN index-only scan for src column cid {} (skip reading data pages)", src_cid);
1060
1061
0
    return Status::OK();
1062
0
}
1063
1064
545
Status SegmentIterator::_get_row_ranges_from_conditions(RowRanges* condition_row_ranges) {
1065
545
    std::set<int32_t> cids;
1066
545
    for (auto& entry : _opts.col_id_to_predicates) {
1067
72
        cids.insert(entry.first);
1068
72
    }
1069
1070
545
    {
1071
545
        SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_dict_ns);
1072
        /// Low cardinality optimization is currently not very stable, so to prevent data corruption,
1073
        /// we are temporarily disabling its use in data compaction.
1074
        // TODO: enable it in not only ReaderTyper::READER_QUERY but also other reader types.
1075
545
        if (_opts.io_ctx.reader_type == ReaderType::READER_QUERY) {
1076
78
            RowRanges dict_row_ranges = RowRanges::create_single(num_rows());
1077
78
            for (auto cid : cids) {
1078
72
                if (!_segment->can_apply_predicate_safely(
1079
72
                            cid, *_schema, _opts.target_cast_type_for_variants, _opts)) {
1080
0
                    continue;
1081
0
                }
1082
72
                DCHECK(_opts.col_id_to_predicates.count(cid) > 0);
1083
72
                RETURN_IF_ERROR(_column_iterators[cid]->get_row_ranges_by_dict(
1084
72
                        _opts.col_id_to_predicates.at(cid).get(), &dict_row_ranges));
1085
1086
72
                if (dict_row_ranges.is_empty()) {
1087
0
                    break;
1088
0
                }
1089
72
            }
1090
1091
78
            if (dict_row_ranges.is_empty()) {
1092
0
                RowRanges::ranges_intersection(*condition_row_ranges, dict_row_ranges,
1093
0
                                               condition_row_ranges);
1094
0
                _opts.stats->segment_dict_filtered++;
1095
0
                _opts.stats->filtered_segment_number++;
1096
0
                return Status::OK();
1097
0
            }
1098
78
        }
1099
545
    }
1100
1101
545
    size_t pre_size = 0;
1102
545
    {
1103
545
        SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_bf_ns);
1104
        // first filter data by bloom filter index
1105
        // bloom filter index only use CondColumn
1106
545
        RowRanges bf_row_ranges = RowRanges::create_single(num_rows());
1107
545
        for (auto& cid : cids) {
1108
72
            DCHECK(_opts.col_id_to_predicates.count(cid) > 0);
1109
72
            if (!_segment->can_apply_predicate_safely(cid, *_schema,
1110
72
                                                      _opts.target_cast_type_for_variants, _opts)) {
1111
0
                continue;
1112
0
            }
1113
            // get row ranges by bf index of this column,
1114
72
            RowRanges column_bf_row_ranges = RowRanges::create_single(num_rows());
1115
72
            RETURN_IF_ERROR(_column_iterators[cid]->get_row_ranges_by_bloom_filter(
1116
72
                    _opts.col_id_to_predicates.at(cid).get(), &column_bf_row_ranges));
1117
72
            RowRanges::ranges_intersection(bf_row_ranges, column_bf_row_ranges, &bf_row_ranges);
1118
72
        }
1119
1120
545
        pre_size = condition_row_ranges->count();
1121
545
        RowRanges::ranges_intersection(*condition_row_ranges, bf_row_ranges, condition_row_ranges);
1122
545
        _opts.stats->rows_bf_filtered += (pre_size - condition_row_ranges->count());
1123
545
    }
1124
1125
0
    {
1126
545
        SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_zonemap_ns);
1127
545
        RowRanges zone_map_row_ranges = RowRanges::create_single(num_rows());
1128
        // second filter data by zone map
1129
545
        for (const auto& cid : cids) {
1130
72
            DCHECK(_opts.col_id_to_predicates.count(cid) > 0);
1131
72
            if (!_segment->can_apply_predicate_safely(cid, *_schema,
1132
72
                                                      _opts.target_cast_type_for_variants, _opts)) {
1133
0
                continue;
1134
0
            }
1135
72
            if (_segment->is_tso_placeholder_col(cid, *_schema, _opts)) {
1136
                // skip untrustworthy tso placeholder zonemap
1137
                // if possible already be pruned as a whole before,
1138
                // so just skip
1139
0
                continue;
1140
0
            }
1141
            // do not check zonemap if predicate does not support zonemap
1142
72
            if (!_opts.col_id_to_predicates.at(cid)->support_zonemap()) {
1143
0
                VLOG_DEBUG << "skip zonemap for column " << cid;
1144
0
                continue;
1145
0
            }
1146
            // get row ranges by zone map of this column,
1147
72
            RowRanges column_row_ranges = RowRanges::create_single(num_rows());
1148
72
            RETURN_IF_ERROR(_column_iterators[cid]->get_row_ranges_by_zone_map(
1149
72
                    _opts.col_id_to_predicates.at(cid).get(),
1150
72
                    _opts.del_predicates_for_zone_map.count(cid) > 0
1151
72
                            ? &(_opts.del_predicates_for_zone_map.at(cid))
1152
72
                            : nullptr,
1153
72
                    &column_row_ranges));
1154
            // intersect different columns's row ranges to get final row ranges by zone map
1155
72
            RowRanges::ranges_intersection(zone_map_row_ranges, column_row_ranges,
1156
72
                                           &zone_map_row_ranges);
1157
72
        }
1158
1159
545
        pre_size = condition_row_ranges->count();
1160
545
        RowRanges::ranges_intersection(*condition_row_ranges, zone_map_row_ranges,
1161
545
                                       condition_row_ranges);
1162
1163
545
        size_t pre_size2 = condition_row_ranges->count();
1164
545
        RowRanges::ranges_intersection(*condition_row_ranges, zone_map_row_ranges,
1165
545
                                       condition_row_ranges);
1166
545
        _opts.stats->rows_stats_rp_filtered += (pre_size2 - condition_row_ranges->count());
1167
545
        _opts.stats->rows_stats_filtered += (pre_size - condition_row_ranges->count());
1168
545
    }
1169
1170
0
    {
1171
545
        SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_zonemap_ns);
1172
545
        if (!_common_expr_ctxs_push_down.empty()) {
1173
6
            const auto pre_expr_zonemap_size = condition_row_ranges->count();
1174
6
            RETURN_IF_ERROR(_apply_expr_zonemap_to_row_ranges(_common_expr_ctxs_push_down, 0,
1175
6
                                                              condition_row_ranges));
1176
6
            _opts.stats->rows_stats_filtered +=
1177
6
                    (pre_expr_zonemap_size - condition_row_ranges->count());
1178
6
        }
1179
545
    }
1180
1181
545
    return Status::OK();
1182
545
}
1183
1184
0
bool SegmentIterator::_is_literal_node(const TExprNodeType::type& node_type) {
1185
0
    switch (node_type) {
1186
0
    case TExprNodeType::BOOL_LITERAL:
1187
0
    case TExprNodeType::INT_LITERAL:
1188
0
    case TExprNodeType::LARGE_INT_LITERAL:
1189
0
    case TExprNodeType::FLOAT_LITERAL:
1190
0
    case TExprNodeType::DECIMAL_LITERAL:
1191
0
    case TExprNodeType::STRING_LITERAL:
1192
0
    case TExprNodeType::DATE_LITERAL:
1193
0
    case TExprNodeType::TIMEV2_LITERAL:
1194
0
        return true;
1195
0
    default:
1196
0
        return false;
1197
0
    }
1198
0
}
1199
1200
14
Status SegmentIterator::_extract_common_expr_columns(const VExprSPtr& expr) {
1201
14
    auto& children = expr->children();
1202
22
    for (int i = 0; i < children.size(); ++i) {
1203
8
        RETURN_IF_ERROR(_extract_common_expr_columns(children[i]));
1204
8
    }
1205
1206
14
    auto node_type = expr->node_type();
1207
14
    if (node_type == TExprNodeType::SLOT_REF) {
1208
6
        auto slot_expr = std::dynamic_pointer_cast<doris::VSlotRef>(expr);
1209
6
        auto cid = _schema->column_id(slot_expr->column_id());
1210
6
        _is_common_expr_column[cid] = true;
1211
6
        _common_expr_columns.insert(cid);
1212
8
    } else if (node_type == TExprNodeType::VIRTUAL_SLOT_REF) {
1213
0
        std::shared_ptr<VirtualSlotRef> virtual_slot_ref =
1214
0
                std::dynamic_pointer_cast<VirtualSlotRef>(expr);
1215
0
        RETURN_IF_ERROR(_extract_common_expr_columns(virtual_slot_ref->get_virtual_column_expr()));
1216
0
    }
1217
1218
14
    return Status::OK();
1219
14
}
1220
1221
53
bool SegmentIterator::_check_apply_by_inverted_index(std::shared_ptr<ColumnPredicate> pred) {
1222
53
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_inverted_index_query) {
1223
0
        return false;
1224
0
    }
1225
53
    auto pred_column_id = pred->column_id();
1226
53
    if (_index_iterators[pred_column_id] == nullptr) {
1227
        //this column without inverted index
1228
0
        return false;
1229
0
    }
1230
1231
53
    if (_inverted_index_not_support_pred_type(pred->type())) {
1232
0
        return false;
1233
0
    }
1234
1235
53
    if (pred->type() == PredicateType::IN_LIST || pred->type() == PredicateType::NOT_IN_LIST) {
1236
        // in_list or not_in_list predicate produced by runtime filter
1237
0
        if (pred->is_runtime_filter()) {
1238
0
            return false;
1239
0
        }
1240
0
    }
1241
1242
    // UNTOKENIZED strings exceed ignore_above, they are written as null, causing range query errors
1243
53
    if (PredicateTypeTraits::is_range(pred->type()) &&
1244
53
        !IndexReaderHelper::has_bkd_index(_index_iterators[pred_column_id].get())) {
1245
0
        return false;
1246
0
    }
1247
1248
    // Function filter no apply inverted index
1249
53
    if (dynamic_cast<LikeColumnPredicate*>(pred.get()) != nullptr) {
1250
0
        return false;
1251
0
    }
1252
1253
53
    bool handle_by_fulltext = _column_has_fulltext_index(pred_column_id);
1254
53
    if (handle_by_fulltext) {
1255
        // when predicate is leafNode of andNode,
1256
        // can apply 'match query' and 'equal query' and 'list query' for fulltext index.
1257
0
        return pred->type() == PredicateType::MATCH || pred->type() == PredicateType::IS_NULL ||
1258
0
               pred->type() == PredicateType::IS_NOT_NULL ||
1259
0
               PredicateTypeTraits::is_equal_or_list(pred->type());
1260
0
    }
1261
1262
53
    return true;
1263
53
}
1264
1265
// TODO: optimization when all expr can not evaluate by inverted/ann index,
1266
75
Status SegmentIterator::_apply_index_expr() {
1267
75
    bool enable_ann_index_result_cache =
1268
75
            !_opts.runtime_state ||
1269
75
            !_opts.runtime_state->query_options().__isset.enable_ann_index_result_cache ||
1270
75
            _opts.runtime_state->query_options().enable_ann_index_result_cache;
1271
1272
75
    for (const auto& expr_ctx : _common_expr_ctxs_push_down) {
1273
18
        if (Status st = expr_ctx->evaluate_inverted_index(num_rows()); !st.ok()) {
1274
0
            if (_downgrade_without_index(st) || st.code() == ErrorCode::NOT_IMPLEMENTED_ERROR) {
1275
0
                continue;
1276
0
            } else {
1277
                // other code is not to be handled, we should just break
1278
0
                LOG(WARNING) << "failed to evaluate inverted index for expr_ctx: "
1279
0
                             << expr_ctx->root()->debug_string()
1280
0
                             << ", error msg: " << st.to_string();
1281
0
                return st;
1282
0
            }
1283
0
        }
1284
18
    }
1285
1286
    // Evaluate inverted index for virtual column MATCH expressions (projections).
1287
    // Unlike common exprs which filter rows, these only compute index result bitmaps
1288
    // for later materialization via fast_execute().
1289
75
    for (auto& [cid, expr_ctx] : _virtual_column_exprs) {
1290
0
        if (expr_ctx->get_index_context() == nullptr) {
1291
0
            continue;
1292
0
        }
1293
0
        if (Status st = expr_ctx->evaluate_inverted_index(num_rows()); !st.ok()) {
1294
0
            if (_downgrade_without_index(st) || st.code() == ErrorCode::NOT_IMPLEMENTED_ERROR) {
1295
0
                continue;
1296
0
            } else {
1297
0
                LOG(WARNING) << "failed to evaluate inverted index for virtual column expr: "
1298
0
                             << expr_ctx->root()->debug_string()
1299
0
                             << ", error msg: " << st.to_string();
1300
0
                return st;
1301
0
            }
1302
0
        }
1303
0
    }
1304
1305
    // Apply ann range search
1306
75
    for (const auto& expr_ctx : _common_expr_ctxs_push_down) {
1307
18
        segment_v2::AnnIndexStats ann_index_stats;
1308
18
        size_t origin_rows = _row_bitmap.cardinality();
1309
18
        bool ann_range_search_executed = false;
1310
18
        RETURN_IF_ERROR(expr_ctx->evaluate_ann_range_search(
1311
18
                _index_iterators, _schema->column_ids(), _column_iterators,
1312
18
                _common_expr_to_slotref_map, num_rows(), _row_bitmap, ann_index_stats,
1313
18
                enable_ann_index_result_cache, &ann_range_search_executed));
1314
18
        if (ann_range_search_executed) {
1315
0
            _opts.stats->ann_index_range_search_cnt++;
1316
0
        }
1317
18
        _opts.stats->rows_ann_index_range_filtered += (origin_rows - _row_bitmap.cardinality());
1318
18
        _opts.stats->ann_index_load_ns += ann_index_stats.load_index_costs_ns.value();
1319
18
        _opts.stats->ann_index_range_search_ns += ann_index_stats.search_costs_ns.value();
1320
18
        _opts.stats->ann_ivf_on_disk_load_ns += ann_index_stats.ivf_on_disk_load_costs_ns.value();
1321
18
        _opts.stats->ann_ivf_on_disk_cache_hit_cnt +=
1322
18
                ann_index_stats.ivf_on_disk_cache_hit_cnt.value();
1323
18
        _opts.stats->ann_ivf_on_disk_cache_miss_cnt +=
1324
18
                ann_index_stats.ivf_on_disk_cache_miss_cnt.value();
1325
18
        _opts.stats->ann_range_engine_search_ns += ann_index_stats.engine_search_ns.value();
1326
18
        _opts.stats->ann_range_result_convert_ns += ann_index_stats.result_process_costs_ns.value();
1327
18
        _opts.stats->ann_range_engine_convert_ns += ann_index_stats.engine_convert_ns.value();
1328
18
        _opts.stats->ann_range_pre_process_ns += ann_index_stats.engine_prepare_ns.value();
1329
18
        _opts.stats->ann_fall_back_brute_force_cnt += ann_index_stats.fall_back_brute_force_cnt;
1330
18
        _opts.stats->ann_range_fallback_by_small_candidate_cnt +=
1331
18
                ann_index_stats.range_fallback_by_small_candidate_cnt;
1332
18
        _opts.stats->ann_range_fallback_small_candidate_rows +=
1333
18
                ann_index_stats.range_fallback_small_candidate_rows;
1334
18
        _opts.stats->ann_index_range_cache_hits += ann_index_stats.range_cache_hits.value();
1335
18
    }
1336
1337
75
    return Status::OK();
1338
75
}
1339
1340
0
bool SegmentIterator::_downgrade_without_index(Status res, bool need_remaining) {
1341
0
    bool is_fallback =
1342
0
            _opts.runtime_state->query_options().enable_fallback_on_missing_inverted_index;
1343
0
    if ((res.code() == ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND && is_fallback) ||
1344
0
        res.code() == ErrorCode::INVERTED_INDEX_BYPASS ||
1345
0
        res.code() == ErrorCode::INVERTED_INDEX_EVALUATE_SKIPPED ||
1346
0
        (res.code() == ErrorCode::INVERTED_INDEX_NO_TERMS && need_remaining) ||
1347
0
        res.code() == ErrorCode::INVERTED_INDEX_FILE_CORRUPTED) {
1348
        // 1. INVERTED_INDEX_FILE_NOT_FOUND means index file has not been built,
1349
        //    usually occurs when creating a new index, queries can be downgraded
1350
        //    without index.
1351
        // 2. INVERTED_INDEX_BYPASS means the hit of condition by index
1352
        //    has reached the optimal limit, downgrade without index query can
1353
        //    improve query performance.
1354
        // 3. INVERTED_INDEX_EVALUATE_SKIPPED means the inverted index is not
1355
        //    suitable for executing this predicate, skipped it and filter data
1356
        //    by function later.
1357
        // 4. INVERTED_INDEX_NO_TERMS means the column has fulltext index,
1358
        //    but the column condition value no terms in specified parser,
1359
        //    such as: where A = '' and B = ','
1360
        //    the predicate of A and B need downgrade without index query.
1361
        // 5. INVERTED_INDEX_FILE_CORRUPTED means the index file is corrupted,
1362
        //    such as when index segment files are not generated
1363
        // above case can downgrade without index query
1364
0
        _opts.stats->inverted_index_downgrade_count++;
1365
0
        if (!res.is<ErrorCode::INVERTED_INDEX_BYPASS>()) {
1366
0
            LOG(INFO) << "will downgrade without index to evaluate predicate, because of res: "
1367
0
                      << res;
1368
0
        } else {
1369
0
            VLOG_DEBUG << "will downgrade without index to evaluate predicate, because of res: "
1370
0
                       << res;
1371
0
        }
1372
0
        return true;
1373
0
    }
1374
0
    return false;
1375
0
}
1376
1377
106
bool SegmentIterator::_column_has_fulltext_index(int32_t cid) {
1378
106
    bool has_fulltext_index =
1379
106
            _index_iterators[cid] != nullptr &&
1380
106
            _index_iterators[cid]->get_reader(InvertedIndexReaderType::FULLTEXT) &&
1381
106
            _index_iterators[cid]->get_reader(InvertedIndexReaderType::STRING_TYPE) == nullptr;
1382
1383
106
    return has_fulltext_index;
1384
106
}
1385
1386
53
inline bool SegmentIterator::_inverted_index_not_support_pred_type(const PredicateType& type) {
1387
53
    return type == PredicateType::BF;
1388
53
}
1389
1390
Status SegmentIterator::_apply_inverted_index_on_column_predicate(
1391
        std::shared_ptr<ColumnPredicate> pred,
1392
53
        std::vector<std::shared_ptr<ColumnPredicate>>& remaining_predicates, bool* continue_apply) {
1393
53
    if (!_check_apply_by_inverted_index(pred)) {
1394
0
        remaining_predicates.emplace_back(pred);
1395
53
    } else {
1396
53
        bool need_remaining_after_evaluate = _column_has_fulltext_index(pred->column_id()) &&
1397
53
                                             PredicateTypeTraits::is_equal_or_list(pred->type());
1398
53
        Status res =
1399
53
                pred->evaluate(_storage_name_and_type[pred->column_id()],
1400
53
                               _index_iterators[pred->column_id()].get(), num_rows(), &_row_bitmap);
1401
53
        if (!res.ok()) {
1402
0
            if (_downgrade_without_index(res, need_remaining_after_evaluate)) {
1403
0
                remaining_predicates.emplace_back(pred);
1404
0
                return Status::OK();
1405
0
            }
1406
0
            LOG(WARNING) << "failed to evaluate index"
1407
0
                         << ", column predicate type: " << pred->pred_type_string(pred->type())
1408
0
                         << ", error msg: " << res;
1409
0
            return res;
1410
0
        }
1411
1412
53
        if (_row_bitmap.isEmpty()) {
1413
            // all rows have been pruned, no need to process further predicates
1414
0
            *continue_apply = false;
1415
0
        }
1416
1417
53
        if (need_remaining_after_evaluate) {
1418
0
            remaining_predicates.emplace_back(pred);
1419
0
            return Status::OK();
1420
0
        }
1421
53
        if (!pred->is_runtime_filter()) {
1422
53
            _column_predicate_index_exec_status[pred->column_id()][pred] = true;
1423
53
        }
1424
53
    }
1425
53
    return Status::OK();
1426
53
}
1427
1428
37.1k
bool SegmentIterator::_need_read_data(ColumnId cid) {
1429
37.1k
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_no_need_read_data_opt) {
1430
0
        return true;
1431
0
    }
1432
37.1k
    if (_can_skip_reading_extra_column(cid)) {
1433
0
        return false;
1434
0
    }
1435
    // only support DUP_KEYS and UNIQUE_KEYS with MOW
1436
37.1k
    if (!((_opts.tablet_schema->keys_type() == KeysType::DUP_KEYS ||
1437
37.1k
           (_opts.tablet_schema->keys_type() == KeysType::UNIQUE_KEYS &&
1438
19.8k
            _opts.enable_unique_key_merge_on_write)))) {
1439
16.7k
        return true;
1440
16.7k
    }
1441
    // this is a virtual column, we always need to read data
1442
20.4k
    if (_virtual_column_exprs.contains(cid)) {
1443
0
        return true;
1444
0
    }
1445
1446
    // if there is a delete predicate, we always need to read data
1447
20.4k
    if (_has_delete_predicate(cid)) {
1448
1.69k
        return true;
1449
1.69k
    }
1450
18.7k
    if (_output_columns.count(-1)) {
1451
        // if _output_columns contains -1, it means that the light
1452
        // weight schema change may not be enabled or other reasons
1453
        // caused the column unique_id not be set, to prevent errors
1454
        // occurring, return true here that column data needs to be read
1455
0
        return true;
1456
0
    }
1457
18.7k
    const auto& column = _opts.tablet_schema->column(cid);
1458
    // Different subcolumns may share the same parent_unique_id, so we choose to abandon this optimization.
1459
18.7k
    if (column.is_extracted_column() &&
1460
18.7k
        _opts.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
1461
538
        return true;
1462
538
    }
1463
18.1k
    int32_t unique_id = column.unique_id();
1464
18.1k
    if (unique_id < 0) {
1465
9
        unique_id = column.parent_unique_id();
1466
9
    }
1467
    // A column can skip data reads when its predicates have already been fully resolved.
1468
    // zonemap_always_true_pred_cols is produced only for non-key columns because key columns
1469
    // must remain readable for short-key range seeks.
1470
18.1k
    const bool used_by_common_expr =
1471
18.1k
            cid < _is_common_expr_column.size() && _is_common_expr_column[cid];
1472
18.1k
    const bool zonemap_always_true_filter_column =
1473
18.1k
            _opts.zonemap_always_true_pred_cols.contains(cid);
1474
18.1k
    DCHECK(!zonemap_always_true_filter_column || !column.is_key());
1475
18.1k
    const bool no_need_read_filter_column =
1476
18.1k
            (_need_read_data_indices.contains(cid) && !_need_read_data_indices[cid]) ||
1477
18.1k
            (zonemap_always_true_filter_column && !used_by_common_expr);
1478
18.1k
    if ((no_need_read_filter_column && !_output_columns.contains(unique_id)) ||
1479
18.1k
        (no_need_read_filter_column && _output_columns.count(unique_id) == 1 &&
1480
18.1k
         _opts.push_down_agg_type_opt == TPushAggOp::COUNT_ON_INDEX)) {
1481
41
        VLOG_DEBUG << "SegmentIterator no need read data for column: "
1482
0
                   << _opts.tablet_schema->column_by_uid(unique_id).name();
1483
41
        return false;
1484
41
    }
1485
18.1k
    return true;
1486
18.1k
}
1487
1488
71
Status SegmentIterator::_apply_inverted_index() {
1489
71
    std::vector<std::shared_ptr<ColumnPredicate>> remaining_predicates;
1490
71
    std::set<std::shared_ptr<ColumnPredicate>> no_need_to_pass_column_predicate_set;
1491
1492
71
    for (auto pred : _col_predicates) {
1493
53
        if (no_need_to_pass_column_predicate_set.count(pred) > 0) {
1494
0
            continue;
1495
53
        } else {
1496
53
            bool continue_apply = true;
1497
53
            RETURN_IF_ERROR(_apply_inverted_index_on_column_predicate(pred, remaining_predicates,
1498
53
                                                                      &continue_apply));
1499
53
            if (!continue_apply) {
1500
0
                break;
1501
0
            }
1502
53
        }
1503
53
    }
1504
1505
71
    _col_predicates = std::move(remaining_predicates);
1506
71
    return Status::OK();
1507
71
}
1508
1509
/**
1510
 * @brief Checks if all conditions related to a specific column have passed in both
1511
 * `_column_predicate_inverted_index_status` and `_common_expr_inverted_index_status`.
1512
 *
1513
 * This function first checks the conditions in `_column_predicate_inverted_index_status`
1514
 * for the given `ColumnId`. If all conditions pass, it sets `default_return` to `true`.
1515
 * It then checks the conditions in `_common_expr_inverted_index_status` for the same column.
1516
 *
1517
 * The function returns `true` if all conditions in both maps pass. If any condition fails
1518
 * in either map, the function immediately returns `false`. If the column does not exist
1519
 * in one of the maps, the function returns `default_return`.
1520
 *
1521
 * @param cid The ColumnId of the column to check.
1522
 * @param default_return The default value to return if the column is not found in the status maps.
1523
 * @return true if all conditions in both status maps pass, or if the column is not found
1524
 *         and `default_return` is true.
1525
 * @return false if any condition in either status map fails, or if the column is not found
1526
 *         and `default_return` is false.
1527
 */
1528
bool SegmentIterator::_check_all_conditions_passed_inverted_index_for_column(ColumnId cid,
1529
169
                                                                             bool default_return) {
1530
169
    auto pred_it = _column_predicate_index_exec_status.find(cid);
1531
169
    if (pred_it != _column_predicate_index_exec_status.end()) {
1532
55
        const auto& pred_map = pred_it->second;
1533
55
        bool pred_passed = std::all_of(pred_map.begin(), pred_map.end(),
1534
55
                                       [](const auto& pred_entry) { return pred_entry.second; });
1535
55
        if (!pred_passed) {
1536
1
            return false;
1537
54
        } else {
1538
54
            default_return = true;
1539
54
        }
1540
55
    }
1541
1542
168
    auto expr_it = _common_expr_index_exec_status.find(cid);
1543
168
    if (expr_it != _common_expr_index_exec_status.end()) {
1544
18
        const auto& expr_map = expr_it->second;
1545
18
        return std::all_of(expr_map.begin(), expr_map.end(),
1546
18
                           [](const auto& expr_entry) { return expr_entry.second; });
1547
18
    }
1548
150
    return default_return;
1549
168
}
1550
1551
4.39k
Status SegmentIterator::_init_return_column_iterators() {
1552
4.39k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_return_column_iterators_timer_ns);
1553
4.39k
    if (_cur_rowid >= num_rows()) {
1554
0
        return Status::OK();
1555
0
    }
1556
1557
10.4k
    for (auto cid : _schema->column_ids()) {
1558
10.4k
        if (_schema->column(cid)->name() == BeConsts::ROWID_COL) {
1559
0
            _column_iterators[cid].reset(
1560
0
                    new RowIdColumnIterator(_opts.tablet_id, _opts.rowset_id, _segment->id()));
1561
0
            continue;
1562
0
        }
1563
1564
10.4k
        if (_schema->column(cid)->name().starts_with(BeConsts::GLOBAL_ROWID_COL)) {
1565
0
            auto& id_file_map = _opts.runtime_state->get_id_file_map();
1566
0
            uint32_t file_id = id_file_map->get_file_mapping_id(std::make_shared<FileMapping>(
1567
0
                    _opts.tablet_id, _opts.rowset_id, _segment->id()));
1568
0
            _column_iterators[cid].reset(new RowIdColumnIteratorV2(
1569
0
                    IdManager::ID_VERSION, BackendOptions::get_backend_id(), file_id));
1570
0
            continue;
1571
0
        }
1572
1573
10.4k
        if (_schema->column(cid)->name().starts_with(BeConsts::VIRTUAL_COLUMN_PREFIX)) {
1574
0
            _column_iterators[cid] = std::make_unique<VirtualColumnIterator>();
1575
0
            continue;
1576
0
        }
1577
1578
10.4k
        std::set<ColumnId> del_cond_id_set;
1579
10.4k
        _opts.delete_condition_predicates->get_all_column_ids(del_cond_id_set);
1580
10.4k
        std::vector<bool> tmp_is_pred_column;
1581
10.4k
        tmp_is_pred_column.resize(_schema->columns().size(), false);
1582
10.4k
        for (auto predicate : _col_predicates) {
1583
154
            auto p_cid = predicate->column_id();
1584
154
            tmp_is_pred_column[p_cid] = true;
1585
154
        }
1586
        // handle delete_condition
1587
10.4k
        for (auto d_cid : del_cond_id_set) {
1588
1.32k
            tmp_is_pred_column[d_cid] = true;
1589
1.32k
        }
1590
1591
10.4k
        if (_column_iterators[cid] == nullptr) {
1592
10.4k
            RETURN_IF_ERROR(_segment->new_column_iterator(_opts.tablet_schema->column(cid),
1593
10.4k
                                                          &_column_iterators[cid], &_opts,
1594
10.4k
                                                          &_variant_sparse_column_cache));
1595
10.4k
            ColumnIteratorOptions iter_opts {
1596
10.4k
                    .use_page_cache = _opts.use_page_cache,
1597
                    // If the col is predicate column, then should read the last page to check
1598
                    // if the column is full dict encoding
1599
10.4k
                    .is_predicate_column = tmp_is_pred_column[cid],
1600
10.4k
                    .file_reader = _file_reader.get(),
1601
10.4k
                    .stats = _opts.stats,
1602
10.4k
                    .io_ctx = _opts.io_ctx,
1603
10.4k
            };
1604
10.4k
            RETURN_IF_ERROR(_column_iterators[cid]->init(iter_opts));
1605
10.4k
        }
1606
10.4k
    }
1607
1608
4.39k
#ifndef NDEBUG
1609
4.39k
    for (const auto& entry : _virtual_column_exprs) {
1610
0
        ColumnId vir_col_cid = entry.first;
1611
0
        DCHECK(_column_iterators[vir_col_cid] != nullptr)
1612
0
                << "Virtual column iterator for " << vir_col_cid << " should not be null";
1613
0
        ColumnIterator* column_iter = _column_iterators[vir_col_cid].get();
1614
0
        DCHECK(dynamic_cast<VirtualColumnIterator*>(column_iter) != nullptr)
1615
0
                << "Virtual column iterator for " << vir_col_cid
1616
0
                << " should be VirtualColumnIterator";
1617
0
    }
1618
4.39k
#endif
1619
4.39k
    return Status::OK();
1620
4.39k
}
1621
1622
4.39k
Status SegmentIterator::_init_index_iterators() {
1623
4.39k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_index_iterators_timer_ns);
1624
4.39k
    if (_cur_rowid >= num_rows()) {
1625
0
        return Status::OK();
1626
0
    }
1627
1628
4.39k
    _index_query_context = std::make_shared<IndexQueryContext>();
1629
4.39k
    _index_query_context->io_ctx = &_opts.io_ctx;
1630
4.39k
    _index_query_context->stats = _opts.stats;
1631
4.39k
    _index_query_context->runtime_state = _opts.runtime_state;
1632
1633
4.39k
    if (_score_runtime) {
1634
0
        _index_query_context->collection_statistics = _opts.collection_statistics;
1635
0
        _index_query_context->collection_similarity = std::make_shared<CollectionSimilarity>();
1636
0
        _index_query_context->query_limit = _score_runtime->get_limit();
1637
0
        _index_query_context->is_asc = _score_runtime->is_asc();
1638
0
    }
1639
1640
    // Inverted index iterators
1641
10.4k
    for (auto cid : _schema->column_ids()) {
1642
        // Use segment’s own index_meta, for compatibility with future indexing needs to default to lowercase.
1643
10.4k
        if (_index_iterators[cid] == nullptr) {
1644
            // Scan-time Variant path placeholders retain the Variant storage type. Use their
1645
            // parent unique id and path to locate the extracted column's inverted-index metadata.
1646
10.4k
            const auto& column = _opts.tablet_schema->column(cid);
1647
10.4k
            std::vector<const TabletIndex*> inverted_indexs;
1648
            // Keep shared_ptr alive to prevent use-after-free when accessing raw pointers
1649
10.4k
            TabletIndexes inverted_indexs_holder;
1650
            // If the column is an extracted column, we need to find the sub-column in the parent column reader.
1651
10.4k
            std::shared_ptr<ColumnReader> column_reader;
1652
10.4k
            if (column.is_extracted_column()) {
1653
270
                if (!_segment->_column_reader_cache->get_column_reader(
1654
270
                            column.parent_unique_id(), &column_reader, _opts.stats) ||
1655
270
                    column_reader == nullptr) {
1656
0
                    continue;
1657
0
                }
1658
270
                auto* variant_reader = assert_cast<VariantColumnReader*>(column_reader.get());
1659
270
                DataTypePtr data_type = _storage_name_and_type[cid].second;
1660
270
                if (data_type != nullptr &&
1661
270
                    data_type->get_primitive_type() == PrimitiveType::TYPE_VARIANT) {
1662
52
                    DataTypePtr inferred_type;
1663
52
                    Status st = variant_reader->infer_data_type_for_path(
1664
52
                            &inferred_type, column, _opts, _segment->_column_reader_cache.get());
1665
52
                    if (st.ok() && inferred_type != nullptr) {
1666
52
                        data_type = inferred_type;
1667
52
                    }
1668
52
                }
1669
270
                inverted_indexs_holder = variant_reader->find_subcolumn_tablet_indexes(
1670
270
                        column, data_type, _opts.stats);
1671
                // Extract raw pointers from shared_ptr for iteration
1672
270
                for (const auto& index_ptr : inverted_indexs_holder) {
1673
99
                    inverted_indexs.push_back(index_ptr.get());
1674
99
                }
1675
270
            }
1676
            // If the column is not an extracted column, we can directly get the inverted index metadata from the tablet schema.
1677
10.1k
            else {
1678
10.1k
                inverted_indexs = _segment->_tablet_schema->inverted_indexs(column);
1679
10.1k
            }
1680
10.4k
            if (column.is_extracted_column() && inverted_indexs.empty() && _opts.stats != nullptr) {
1681
181
                const auto relative_path = column.path_info_ptr()->copy_pop_front().get_path();
1682
181
                const auto diagnostic = fmt::format(
1683
181
                        "[VariantSearchBinding] phase=init_index_iterators "
1684
181
                        "result=no_candidate tablet_id={} rowset_id={} segment_id={} cid={} "
1685
181
                        "logical_path={} relative_path={} materialized_column={}",
1686
181
                        _tablet_id, _segment->rowset_id().to_string(), _segment->id(), cid,
1687
181
                        column.path_info_ptr()->get_path(), relative_path, column.name());
1688
181
                VLOG_DEBUG << diagnostic;
1689
181
                _opts.stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
1690
181
            }
1691
10.4k
            for (const auto& inverted_index : inverted_indexs) {
1692
2.68k
                const bool had_iterator = _index_iterators[cid] != nullptr;
1693
2.68k
                RETURN_IF_ERROR(_segment->new_index_iterator(column, inverted_index, _opts,
1694
2.68k
                                                             &_index_iterators[cid]));
1695
2.68k
                if ((column.is_extracted_column() || column.is_variant_type()) &&
1696
2.68k
                    _opts.stats != nullptr) {
1697
99
                    const auto diagnostic = fmt::format(
1698
99
                            "[VariantSearchBinding] phase=init_index_iterators "
1699
99
                            "result={} tablet_id={} rowset_id={} segment_id={} cid={} "
1700
99
                            "logical_path={} materialized_column={} index_id={} suffix={} "
1701
99
                            "field_pattern={} iterator_state={}",
1702
99
                            _index_iterators[cid] == nullptr ? "no_iterator" : "accepted",
1703
99
                            _tablet_id, _segment->rowset_id().to_string(), _segment->id(), cid,
1704
99
                            column.has_path_info() ? column.path_info_ptr()->get_path()
1705
99
                                                   : column.name(),
1706
99
                            column.name(), inverted_index->index_id(),
1707
99
                            inverted_index->get_index_suffix(), inverted_index->field_pattern(),
1708
99
                            had_iterator ? "preserved" : "created");
1709
99
                    VLOG_DEBUG << diagnostic;
1710
99
                    _opts.stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
1711
99
                }
1712
2.68k
            }
1713
10.4k
            if (_index_iterators[cid] != nullptr) {
1714
2.66k
                _index_iterators[cid]->set_context(_index_query_context);
1715
2.66k
            }
1716
10.4k
        }
1717
10.4k
    }
1718
1719
    // Ann index iterators
1720
10.4k
    for (auto cid : _schema->column_ids()) {
1721
10.4k
        if (_index_iterators[cid] == nullptr) {
1722
7.78k
            const auto& column = _opts.tablet_schema->column(cid);
1723
7.78k
            const auto* index_meta = _segment->_tablet_schema->ann_index(column);
1724
7.78k
            if (index_meta) {
1725
1
                RETURN_IF_ERROR(_segment->new_index_iterator(column, index_meta, _opts,
1726
1
                                                             &_index_iterators[cid]));
1727
1728
1
                if (_index_iterators[cid] != nullptr) {
1729
1
                    _index_iterators[cid]->set_context(_index_query_context);
1730
1
                }
1731
1
            }
1732
7.78k
        }
1733
10.4k
    }
1734
1735
4.39k
    return Status::OK();
1736
4.39k
}
1737
1738
Status SegmentIterator::_lookup_ordinal(const RowCursor& key, bool is_include, rowid_t upper_bound,
1739
0
                                        rowid_t* rowid) {
1740
0
    if (_segment->_tablet_schema->keys_type() == UNIQUE_KEYS &&
1741
0
        _segment->get_primary_key_index() != nullptr) {
1742
0
        return _lookup_ordinal_from_pk_index(key, is_include, rowid);
1743
0
    }
1744
0
    return _lookup_ordinal_from_sk_index(key, is_include, upper_bound, rowid);
1745
0
}
1746
1747
// look up one key to get its ordinal at which can get data by using short key index.
1748
// 'upper_bound' is defined the max ordinal the function will search.
1749
// We use upper_bound to reduce search times.
1750
// If we find a valid ordinal, it will be set in rowid and with Status::OK()
1751
// If we can not find a valid key in this segment, we will set rowid to upper_bound
1752
// Otherwise return error.
1753
// 1. get [start, end) ordinal through short key index
1754
// 2. binary search to find exact ordinal that match the input condition
1755
// Make is_include template to reduce branch
1756
Status SegmentIterator::_lookup_ordinal_from_sk_index(const RowCursor& key, bool is_include,
1757
0
                                                      rowid_t upper_bound, rowid_t* rowid) {
1758
0
    const ShortKeyIndexDecoder* sk_index_decoder = _segment->get_short_key_index();
1759
0
    DCHECK(sk_index_decoder != nullptr);
1760
1761
0
    std::string index_key;
1762
0
    key.encode_key_with_padding(&index_key, _segment->_tablet_schema->num_short_key_columns(),
1763
0
                                is_include);
1764
1765
0
    const auto& key_col_ids = key.schema()->column_ids();
1766
1767
0
    ssize_t start_block_id = 0;
1768
0
    auto start_iter = sk_index_decoder->lower_bound(index_key);
1769
0
    if (start_iter.valid()) {
1770
        // Because previous block may contain this key, so we should set rowid to
1771
        // last block's first row.
1772
0
        start_block_id = start_iter.ordinal();
1773
0
        if (start_block_id > 0) {
1774
0
            start_block_id--;
1775
0
        }
1776
0
    } else {
1777
        // When we don't find a valid index item, which means all short key is
1778
        // smaller than input key, this means that this key may exist in the last
1779
        // row block. so we set the rowid to first row of last row block.
1780
0
        start_block_id = sk_index_decoder->num_items() - 1;
1781
0
    }
1782
0
    rowid_t start = cast_set<rowid_t>(start_block_id) * sk_index_decoder->num_rows_per_block();
1783
1784
0
    rowid_t end = upper_bound;
1785
0
    auto end_iter = sk_index_decoder->upper_bound(index_key);
1786
0
    if (end_iter.valid()) {
1787
0
        end = cast_set<rowid_t>(end_iter.ordinal()) * sk_index_decoder->num_rows_per_block();
1788
0
    }
1789
1790
    // binary search to find the exact key
1791
0
    while (start < end) {
1792
0
        rowid_t mid = (start + end) / 2;
1793
0
        RETURN_IF_ERROR(_seek_and_peek(mid));
1794
0
        int cmp = _compare_short_key_with_seek_block(key, key_col_ids);
1795
0
        if (cmp > 0) {
1796
0
            start = mid + 1;
1797
0
        } else if (cmp == 0) {
1798
0
            if (is_include) {
1799
                // lower bound
1800
0
                end = mid;
1801
0
            } else {
1802
                // upper bound
1803
0
                start = mid + 1;
1804
0
            }
1805
0
        } else {
1806
0
            end = mid;
1807
0
        }
1808
0
    }
1809
1810
0
    *rowid = start;
1811
0
    return Status::OK();
1812
0
}
1813
1814
Status SegmentIterator::_lookup_ordinal_from_pk_index(const RowCursor& key, bool is_include,
1815
0
                                                      rowid_t* rowid) {
1816
0
    DCHECK(_segment->_tablet_schema->keys_type() == UNIQUE_KEYS);
1817
0
    const PrimaryKeyIndexReader* pk_index_reader = _segment->get_primary_key_index();
1818
0
    DCHECK(pk_index_reader != nullptr);
1819
1820
0
    std::string index_key;
1821
0
    key.encode_key_with_padding<true>(&index_key, _segment->_tablet_schema->num_key_columns(),
1822
0
                                      is_include);
1823
0
    if (index_key < _segment->min_key()) {
1824
0
        *rowid = 0;
1825
0
        return Status::OK();
1826
0
    } else if (index_key > _segment->max_key()) {
1827
0
        *rowid = num_rows();
1828
0
        return Status::OK();
1829
0
    }
1830
0
    bool exact_match = false;
1831
1832
0
    std::unique_ptr<segment_v2::IndexedColumnIterator> index_iterator;
1833
0
    RETURN_IF_ERROR(pk_index_reader->new_iterator(&index_iterator, _opts.stats, &_opts.io_ctx));
1834
1835
0
    Status status = index_iterator->seek_at_or_after(&index_key, &exact_match);
1836
0
    if (UNLIKELY(!status.ok())) {
1837
0
        *rowid = num_rows();
1838
0
        if (status.is<ENTRY_NOT_FOUND>()) {
1839
0
            return Status::OK();
1840
0
        }
1841
0
        return status;
1842
0
    }
1843
0
    *rowid = cast_set<rowid_t>(index_iterator->get_current_ordinal());
1844
1845
    // The sequence column needs to be removed from primary key index when comparing key
1846
0
    bool has_seq_col = _segment->_tablet_schema->has_sequence_col();
1847
    // Used to get key range from primary key index,
1848
    // for mow with cluster key table, we should get key range from short key index.
1849
0
    DCHECK(_segment->_tablet_schema->cluster_key_uids().empty());
1850
1851
    // if full key is exact_match, the primary key without sequence column should also the same
1852
0
    if (has_seq_col && !exact_match) {
1853
0
        size_t seq_col_length =
1854
0
                _segment->_tablet_schema->column(_segment->_tablet_schema->sequence_col_idx())
1855
0
                        .length() +
1856
0
                1;
1857
0
        auto index_type = DataTypeFactory::instance().create_data_type(
1858
0
                _segment->_pk_index_reader->type(), 1, 0);
1859
0
        auto index_column = index_type->create_column();
1860
0
        size_t num_to_read = 1;
1861
0
        size_t num_read = num_to_read;
1862
0
        RETURN_IF_ERROR(index_iterator->next_batch(&num_read, index_column));
1863
0
        DCHECK(num_to_read == num_read);
1864
1865
0
        Slice sought_key =
1866
0
                Slice(index_column->get_data_at(0).data, index_column->get_data_at(0).size);
1867
0
        Slice sought_key_without_seq =
1868
0
                Slice(sought_key.get_data(), sought_key.get_size() - seq_col_length);
1869
1870
        // compare key
1871
0
        if (Slice(index_key).compare(sought_key_without_seq) == 0) {
1872
0
            exact_match = true;
1873
0
        }
1874
0
    }
1875
1876
    // find the key in primary key index, and the is_include is false, so move
1877
    // to the next row.
1878
0
    if (exact_match && !is_include) {
1879
0
        *rowid += 1;
1880
0
    }
1881
0
    return Status::OK();
1882
0
}
1883
1884
// seek to the row and load that row to _key_cursor
1885
0
Status SegmentIterator::_seek_and_peek(rowid_t rowid) {
1886
0
    {
1887
0
        _opts.stats->block_init_seek_num += 1;
1888
0
        SCOPED_RAW_TIMER(&_opts.stats->block_init_seek_ns);
1889
0
        RETURN_IF_ERROR(_seek_columns(_seek_schema->column_ids(), rowid));
1890
0
    }
1891
0
    size_t num_rows = 1;
1892
1893
    //note(wb) reset _seek_block for memory reuse
1894
    // it is easier to use row based memory layout for clear memory
1895
0
    for (int i = 0; i < _seek_block.size(); i++) {
1896
0
        _seek_block[i]->clear();
1897
0
    }
1898
0
    RETURN_IF_ERROR(_read_columns(_seek_schema->column_ids(), _seek_block, num_rows));
1899
0
    return Status::OK();
1900
0
}
1901
1902
0
Status SegmentIterator::_seek_columns(const std::vector<ColumnId>& column_ids, rowid_t pos) {
1903
0
    for (auto cid : column_ids) {
1904
0
        if (!_need_read_data(cid)) {
1905
0
            continue;
1906
0
        }
1907
0
        RETURN_IF_ERROR(_column_iterators[cid]->seek_to_ordinal(pos));
1908
0
    }
1909
0
    return Status::OK();
1910
0
}
1911
1912
/* ---------------------- for vectorization implementation  ---------------------- */
1913
1914
/**
1915
 *  For storage layer data type, can be measured from two perspectives:
1916
 *  1 Whether the type can be read in a fast way(batch read using SIMD)
1917
 *    Such as integer type and float type, this type can be read in SIMD way.
1918
 *    For the type string/bitmap/hll, they can not be read in batch way, so read this type data is slow.
1919
 *   If a type can be read fast, we can try to eliminate Lazy Materialization, because we think for this type, seek cost > read cost.
1920
 *   This is an estimate, if we want more precise cost, statistics collection is necessary(this is a todo).
1921
 *   In short, when returned non-pred columns contains string/hll/bitmap, we using Lazy Materialization.
1922
 *   Otherwise, we disable it.
1923
 *
1924
 *   When Lazy Materialization enable, we need to read column at least two times.
1925
 *   First time to read Pred col, second time to read non-pred.
1926
 *   Here's an interesting question to research, whether read Pred col once is the best plan.
1927
 *   (why not read Pred col twice or more?)
1928
 *
1929
 *   When Lazy Materialization disable, we just need to read once.
1930
 *
1931
 *
1932
 *  2 Whether the predicate type can be evaluate in a fast way(using SIMD to eval pred)
1933
 *    Such as integer type and float type, they can be eval fast.
1934
 *    But for BloomFilter/string/date, they eval slow.
1935
 *    If a type can be eval fast, we use vectorization to eval it.
1936
 *    Otherwise, we use short-circuit to eval it.
1937
 *
1938
 *
1939
 */
1940
1941
// todo(wb) need a UT here
1942
4.39k
Status SegmentIterator::_vec_init_lazy_materialization() {
1943
4.39k
    _is_pred_column.resize(_schema->columns().size(), false);
1944
1945
    // including short/vec/delete pred
1946
4.39k
    std::set<ColumnId> pred_column_ids;
1947
4.39k
    _lazy_materialization_read = false;
1948
1949
4.39k
    std::set<ColumnId> del_cond_id_set;
1950
4.39k
    _opts.delete_condition_predicates->get_all_column_ids(del_cond_id_set);
1951
1952
4.39k
    std::set<std::shared_ptr<const ColumnPredicate>> delete_predicate_set {};
1953
4.39k
    _opts.delete_condition_predicates->get_all_column_predicate(delete_predicate_set);
1954
4.39k
    for (auto predicate : delete_predicate_set) {
1955
467
        if (PredicateTypeTraits::is_range(predicate->type())) {
1956
327
            _delete_range_column_ids.push_back(predicate->column_id());
1957
327
        } else if (PredicateTypeTraits::is_bloom_filter(predicate->type())) {
1958
0
            _delete_bloom_filter_column_ids.push_back(predicate->column_id());
1959
0
        }
1960
467
    }
1961
1962
    // Step1: extract columns that can be lazy materialization
1963
4.39k
    if (!_col_predicates.empty() || !del_cond_id_set.empty()) {
1964
486
        std::set<ColumnId> short_cir_pred_col_id_set; // using set for distinct cid
1965
486
        std::set<ColumnId> vec_pred_col_id_set;
1966
1967
486
        for (auto predicate : _col_predicates) {
1968
19
            auto cid = predicate->column_id();
1969
19
            _is_pred_column[cid] = true;
1970
19
            pred_column_ids.insert(cid);
1971
1972
            // check pred using short eval or vec eval
1973
19
            if (_can_evaluated_by_vectorized(predicate)) {
1974
19
                vec_pred_col_id_set.insert(cid);
1975
19
                _pre_eval_block_predicate.push_back(predicate);
1976
19
            } else {
1977
0
                short_cir_pred_col_id_set.insert(cid);
1978
0
                _short_cir_eval_predicate.push_back(predicate);
1979
0
            }
1980
19
            if (predicate->is_runtime_filter()) {
1981
0
                _filter_info_id.push_back(predicate);
1982
0
            }
1983
19
        }
1984
1985
        // handle delete_condition
1986
486
        if (!del_cond_id_set.empty()) {
1987
467
            short_cir_pred_col_id_set.insert(del_cond_id_set.begin(), del_cond_id_set.end());
1988
467
            pred_column_ids.insert(del_cond_id_set.begin(), del_cond_id_set.end());
1989
1990
467
            for (auto cid : del_cond_id_set) {
1991
467
                _is_pred_column[cid] = true;
1992
467
            }
1993
467
        }
1994
1995
486
        _vec_pred_column_ids.assign(vec_pred_col_id_set.cbegin(), vec_pred_col_id_set.cend());
1996
486
        _short_cir_pred_column_ids.assign(short_cir_pred_col_id_set.cbegin(),
1997
486
                                          short_cir_pred_col_id_set.cend());
1998
486
    }
1999
2000
4.39k
    if (!_vec_pred_column_ids.empty()) {
2001
19
        _is_need_vec_eval = true;
2002
19
    }
2003
4.39k
    if (!_short_cir_pred_column_ids.empty()) {
2004
467
        _is_need_short_eval = true;
2005
467
    }
2006
2007
    // Step2: extract columns that can execute expr context
2008
4.39k
    _is_common_expr_column.resize(_schema->columns().size(), false);
2009
4.39k
    if (!_common_expr_ctxs_push_down.empty()) {
2010
6
        for (const auto& expr_ctx : _common_expr_ctxs_push_down) {
2011
6
            RETURN_IF_ERROR(_extract_common_expr_columns(expr_ctx->root()));
2012
6
        }
2013
6
        if (!_common_expr_columns.empty()) {
2014
6
            _is_need_expr_eval = true;
2015
12
            for (auto cid : _schema->column_ids()) {
2016
                // pred column also needs to be filtered by expr, exclude additional delete condition column.
2017
                // if delete condition column not in the block, no filter is needed
2018
                // and will be removed from _columns_to_filter in the first next_batch.
2019
12
                if (_is_common_expr_column[cid] || _is_pred_column[cid]) {
2020
6
                    auto loc = _schema->column_index(cid);
2021
6
                    _columns_to_filter.push_back(loc);
2022
2023
6
                    const auto field_type = _schema->column(cid)->type();
2024
6
                    if (_is_common_expr_column[cid] && _enable_prune_nested_column &&
2025
6
                        (field_type == FieldType::OLAP_FIELD_TYPE_STRUCT ||
2026
0
                         field_type == FieldType::OLAP_FIELD_TYPE_ARRAY ||
2027
0
                         field_type == FieldType::OLAP_FIELD_TYPE_MAP)) {
2028
0
                        DCHECK(_column_iterators[cid]);
2029
0
                        if (_column_iterators[cid]->read_requirement() ==
2030
0
                                    ColumnIterator::ReadRequirement::PREDICATE &&
2031
0
                            _column_iterators[cid]->has_lazy_read_target()) {
2032
                            // Only split lazy recovery for complex common expr columns that have
2033
                            // both predicate-only and non-predicate nested targets. The two requirement
2034
                            // checks already imply that nested-column pruning happened: without an
2035
                            // explicit predicate sub-path the parent would not be
2036
                            // PREDICATE, and without a pruned non-predicate child there
2037
                            // would be no lazy target to recover after filtering.
2038
0
                            _support_lazy_read_pruned_columns.emplace(cid);
2039
0
                        }
2040
0
                    }
2041
6
                }
2042
12
            }
2043
2044
6
            for (const auto& entry : _virtual_column_exprs) {
2045
0
                _columns_to_filter.push_back(_schema->column_index(entry.first));
2046
0
            }
2047
6
        }
2048
6
    }
2049
2050
    // Step 3: fill non predicate columns and second read column
2051
    // if _schema columns size equal to pred_column_ids size, lazy_materialization_read is false,
2052
    // all columns are lazy materialization columns without non predicte column.
2053
    // If common expr pushdown exists, and expr column is not contained in lazy materialization columns,
2054
    // add to second read column, which will be read after lazy materialization
2055
4.39k
    if (_schema->column_ids().size() > pred_column_ids.size()) {
2056
        // pred_column_ids maybe empty, so that could not set _lazy_materialization_read = true here
2057
        // has to check there is at least one predicate column
2058
10.3k
        for (auto cid : _schema->column_ids()) {
2059
10.3k
            if (!_is_pred_column[cid]) {
2060
9.96k
                if (_is_need_vec_eval || _is_need_short_eval) {
2061
881
                    _lazy_materialization_read = true;
2062
881
                }
2063
9.96k
                if (_is_common_expr_column[cid]) {
2064
6
                    _common_expr_column_ids.push_back(cid);
2065
9.95k
                } else {
2066
9.95k
                    _non_predicate_columns.push_back(cid);
2067
9.95k
                }
2068
9.96k
            }
2069
10.3k
        }
2070
4.33k
    }
2071
2072
    // Step 4: fill first read columns
2073
4.39k
    if (_lazy_materialization_read) {
2074
        // insert pred cid to first_read_columns
2075
429
        for (auto cid : pred_column_ids) {
2076
429
            _predicate_column_ids.push_back(cid);
2077
429
        }
2078
3.96k
    } else if (!_is_need_vec_eval && !_is_need_short_eval && !_is_need_expr_eval) {
2079
12.9k
        for (int i = 0; i < _schema->num_column_ids(); i++) {
2080
9.07k
            auto cid = _schema->column_id(i);
2081
9.07k
            _predicate_column_ids.push_back(cid);
2082
9.07k
        }
2083
3.90k
    } else {
2084
63
        if (_is_need_vec_eval || _is_need_short_eval) {
2085
            // TODO To refactor, because we suppose lazy materialization is better performance.
2086
            // pred exits, but we can eliminate lazy materialization
2087
            // insert pred/non-pred cid to first read columns
2088
57
            std::set<ColumnId> pred_id_set;
2089
57
            pred_id_set.insert(_short_cir_pred_column_ids.begin(),
2090
57
                               _short_cir_pred_column_ids.end());
2091
57
            pred_id_set.insert(_vec_pred_column_ids.begin(), _vec_pred_column_ids.end());
2092
2093
57
            DCHECK(_common_expr_column_ids.empty());
2094
            // _non_predicate_column_ids must be empty. Otherwise _lazy_materialization_read must not false.
2095
114
            for (int i = 0; i < _schema->num_column_ids(); i++) {
2096
57
                auto cid = _schema->column_id(i);
2097
57
                if (pred_id_set.find(cid) != pred_id_set.end()) {
2098
57
                    _predicate_column_ids.push_back(cid);
2099
57
                }
2100
57
            }
2101
57
        } else if (_is_need_expr_eval) {
2102
6
            DCHECK(!_is_need_vec_eval && !_is_need_short_eval);
2103
6
            for (auto cid : _common_expr_columns) {
2104
6
                _predicate_column_ids.push_back(cid);
2105
6
            }
2106
6
        }
2107
63
    }
2108
2109
4.39k
    VLOG_DEBUG << fmt::format(
2110
0
            "Laze materialization init end. "
2111
0
            "lazy_materialization_read: {}, "
2112
0
            "_col_predicates size: {}, "
2113
0
            "_cols_read_by_column_predicate: [{}], "
2114
0
            "_non_predicate_columns: [{}], "
2115
0
            "_cols_read_by_common_expr: [{}], "
2116
0
            "columns_to_filter: [{}], "
2117
0
            "schema_column_id_to_index: [{}]",
2118
0
            _lazy_materialization_read, _col_predicates.size(),
2119
0
            fmt::join(_predicate_column_ids, ","), fmt::join(_non_predicate_columns, ","),
2120
0
            fmt::join(_common_expr_column_ids, ","), fmt::join(_columns_to_filter, ","),
2121
0
            fmt::join(_schema->column_id_to_index(), ","));
2122
4.39k
    return Status::OK();
2123
4.39k
}
2124
2125
19
bool SegmentIterator::_can_evaluated_by_vectorized(std::shared_ptr<ColumnPredicate> predicate) {
2126
19
    auto cid = predicate->column_id();
2127
19
    FieldType field_type = _schema->column(cid)->type();
2128
19
    if (field_type == FieldType::OLAP_FIELD_TYPE_VARIANT) {
2129
        // Use variant cast dst type
2130
0
        field_type = _opts.target_cast_type_for_variants[_schema->column(cid)->name()]
2131
0
                             ->get_storage_field_type();
2132
0
    }
2133
19
    switch (predicate->type()) {
2134
9
    case PredicateType::EQ:
2135
9
    case PredicateType::NE:
2136
9
    case PredicateType::LE:
2137
9
    case PredicateType::LT:
2138
9
    case PredicateType::GE:
2139
19
    case PredicateType::GT: {
2140
19
        if (field_type == FieldType::OLAP_FIELD_TYPE_VARCHAR ||
2141
19
            field_type == FieldType::OLAP_FIELD_TYPE_CHAR ||
2142
19
            field_type == FieldType::OLAP_FIELD_TYPE_STRING) {
2143
5
            return config::enable_low_cardinality_optimize &&
2144
5
                   _opts.io_ctx.reader_type == ReaderType::READER_QUERY &&
2145
5
                   _column_iterators[cid]->is_all_dict_encoding();
2146
14
        } else if (field_type == FieldType::OLAP_FIELD_TYPE_DECIMAL) {
2147
0
            return false;
2148
0
        }
2149
14
        return true;
2150
19
    }
2151
0
    default:
2152
0
        return false;
2153
19
    }
2154
19
}
2155
2156
// These placeholders are used only when the real column data is skipped after
2157
// index/count pushdown has already identified the matching rows. The value is
2158
// irrelevant, but nullable columns must stay non-NULL so COUNT(col) can count
2159
// the matched rows instead of treating every placeholder as NULL.
2160
38
static void insert_many_not_null_defaults(MutableColumnPtr& column, size_t num) {
2161
38
    if (auto* nullable_column = check_and_get_column<ColumnNullable>(column.get())) {
2162
8
        nullable_column->insert_not_null_elements(num);
2163
8
        return;
2164
8
    }
2165
30
    column->insert_many_defaults(num);
2166
30
}
2167
2168
bool SegmentIterator::_prune_column(ColumnId cid, MutableColumnPtr& column,
2169
37.1k
                                    size_t num_of_defaults) {
2170
37.1k
    if (_need_read_data(cid)) {
2171
37.1k
        return false;
2172
37.1k
    }
2173
38
    insert_many_not_null_defaults(column, num_of_defaults);
2174
38
    return true;
2175
37.1k
}
2176
2177
37.1k
bool SegmentIterator::_can_skip_reading_extra_column(ColumnId cid) {
2178
37.1k
    if (!_opts.extra_columns.contains(cid) || _is_pred_column.empty()) {
2179
37.1k
        return false;
2180
37.1k
    }
2181
37.1k
    DCHECK_EQ(_is_pred_column.size(), _is_common_expr_column.size());
2182
0
    DCHECK_LT(cid, _is_pred_column.size());
2183
2184
    // extra_columns is only an optimization hint. The real value is still
2185
    // required when the column participates in expression materialization or
2186
    // any predicate path.
2187
0
    return !_virtual_column_exprs.contains(cid) && !_has_delete_predicate(cid) &&
2188
0
           !_is_pred_column[cid] && !_is_common_expr_column[cid];
2189
37.1k
}
2190
2191
Status SegmentIterator::_read_columns(const std::vector<ColumnId>& column_ids,
2192
0
                                      MutableColumns& column_block, size_t nrows) {
2193
0
    for (auto cid : column_ids) {
2194
0
        auto& column = column_block[cid];
2195
0
        size_t rows_read = nrows;
2196
0
        if (_prune_column(cid, column, rows_read)) {
2197
0
            continue;
2198
0
        }
2199
0
        RETURN_IF_ERROR(_column_iterators[cid]->next_batch(&rows_read, column));
2200
0
        if (nrows != rows_read) {
2201
0
            return Status::Error<ErrorCode::INTERNAL_ERROR>("nrows({}) != rows_read({})", nrows,
2202
0
                                                            rows_read);
2203
0
        }
2204
0
    }
2205
0
    return Status::OK();
2206
0
}
2207
2208
Status SegmentIterator::_init_current_block(Block* block,
2209
                                            std::vector<MutableColumnPtr>& current_columns,
2210
18.0k
                                            uint32_t nrows_read_limit) {
2211
18.0k
    block->clear_column_data(_schema->num_column_ids());
2212
2213
56.0k
    for (size_t i = 0; i < _schema->num_column_ids(); i++) {
2214
37.9k
        auto cid = _schema->column_id(i);
2215
37.9k
        const auto* column_desc = _schema->column(cid);
2216
2217
37.9k
        auto file_column_type = _storage_name_and_type[cid].second;
2218
37.9k
        auto expected_type = Schema::get_data_type_ptr(*column_desc);
2219
37.9k
        if (!_is_pred_column[cid] && !file_column_type->equals(*expected_type)) {
2220
            // The storage layer type is different from schema needed type, so we use storage
2221
            // type to read columns instead of schema type for safety
2222
50
            VLOG_DEBUG << fmt::format(
2223
0
                    "Recreate column with expected type {}, file column type {}, col_name {}, "
2224
0
                    "col_path {}",
2225
0
                    block->get_by_position(i).type->get_name(), file_column_type->get_name(),
2226
0
                    column_desc->name(),
2227
0
                    column_desc->path_info_ptr() == nullptr
2228
0
                            ? ""
2229
0
                            : column_desc->path_info_ptr()->get_path());
2230
            // TODO reuse
2231
50
            current_columns[cid] = file_column_type->create_column();
2232
50
            current_columns[cid]->reserve(nrows_read_limit);
2233
37.8k
        } else {
2234
            // the column in block must clear() here to insert new data
2235
37.8k
            if (_is_pred_column[cid] ||
2236
37.8k
                i >= block->columns()) { //todo(wb) maybe we can release it after output block
2237
2.13k
                if (current_columns[cid].get() == nullptr) {
2238
0
                    return Status::InternalError(
2239
0
                            "SegmentIterator meet invalid column, id={}, name={}", cid,
2240
0
                            _schema->column(cid)->name());
2241
0
                }
2242
2.13k
                current_columns[cid]->clear();
2243
35.7k
            } else { // non-predicate column
2244
35.7k
                current_columns[cid] = std::move(*block->get_by_position(i).column).mutate();
2245
35.7k
                current_columns[cid]->reserve(nrows_read_limit);
2246
35.7k
            }
2247
37.8k
        }
2248
37.9k
    }
2249
2250
18.0k
    for (const auto& entry : _virtual_column_exprs) {
2251
0
        auto cid = entry.first;
2252
0
        current_columns[cid] = ColumnNothing::create(0);
2253
0
        current_columns[cid]->reserve(nrows_read_limit);
2254
0
    }
2255
2256
18.0k
    return Status::OK();
2257
18.0k
}
2258
2259
14.5k
Status SegmentIterator::_output_non_pred_columns(Block* block) {
2260
14.5k
    SCOPED_RAW_TIMER(&_opts.stats->output_col_ns);
2261
14.5k
    VLOG_DEBUG << fmt::format(
2262
0
            "Output non-predicate columns, _non_predicate_columns: [{}], "
2263
0
            "schema_column_id_to_index: [{}]",
2264
0
            fmt::join(_non_predicate_columns, ","), fmt::join(_schema->column_id_to_index(), ","));
2265
14.5k
    RETURN_IF_ERROR(_convert_to_expected_type(_non_predicate_columns));
2266
27.1k
    for (auto cid : _non_predicate_columns) {
2267
27.1k
        auto loc = _schema->column_index(cid);
2268
        // Whether a delete predicate column gets output depends on how the caller builds
2269
        // the block passed to next_batch(). Both calling paths now build the block with
2270
        // only the output schema (return_columns), so delete predicate columns are skipped:
2271
        //
2272
        // 1) VMergeIterator path: block_reset() builds _block using the output schema
2273
        //    (return_columns only), e.g. block has 2 columns {c1, c2}.
2274
        //    Here loc=2 for delete predicate c3, block->columns()=2, so loc < block->columns()
2275
        //    is false, and c3 is skipped.
2276
        //
2277
        // 2) VUnionIterator path: the caller's block is built with only return_columns
2278
        //    (output schema), e.g. block has 2 columns {c1, c2}.
2279
        //    Here loc=2 for c3, block->columns()=2, so loc < block->columns() is false,
2280
        //    and c3 is skipped — same behavior as the VMergeIterator path.
2281
27.1k
        if (loc < block->columns()) {
2282
27.1k
            bool column_in_block_is_nothing = check_and_get_column<const ColumnNothing>(
2283
27.1k
                    block->get_by_position(loc).column.get());
2284
27.1k
            bool column_is_normal = !_virtual_column_exprs.contains(cid);
2285
27.1k
            bool return_column_is_nothing =
2286
27.1k
                    check_and_get_column<const ColumnNothing>(_current_return_columns[cid].get());
2287
27.1k
            VLOG_DEBUG << fmt::format(
2288
0
                    "Cid {} loc {}, column_in_block_is_nothing {}, column_is_normal {}, "
2289
0
                    "return_column_is_nothing {}",
2290
0
                    cid, loc, column_in_block_is_nothing, column_is_normal,
2291
0
                    return_column_is_nothing);
2292
2293
27.1k
            if (column_in_block_is_nothing || column_is_normal) {
2294
27.1k
                block->replace_by_position(loc, std::move(_current_return_columns[cid]));
2295
27.1k
                VLOG_DEBUG << fmt::format(
2296
0
                        "Output non-predicate column, cid: {}, loc: {}, col_name: {}, rows {}", cid,
2297
0
                        loc, _schema->column(cid)->name(),
2298
0
                        block->get_by_position(loc).column->size());
2299
27.1k
            }
2300
            // Means virtual column in block has been materialized(maybe by common expr).
2301
            // so do nothing here.
2302
27.1k
        }
2303
27.1k
    }
2304
14.5k
    return Status::OK();
2305
14.5k
}
2306
2307
/**
2308
 * Reads columns by their index, handling both continuous and discontinuous rowid scenarios.
2309
 *
2310
 * This function is designed to read a specified number of rows (up to nrows_read_limit)
2311
 * from the segment iterator, dealing with both continuous and discontinuous rowid arrays.
2312
 * It operates as follows:
2313
 *
2314
 * 1. Reads a batch of rowids (up to the specified limit), and checks if they are continuous.
2315
 *    Continuous here means that the rowids form an unbroken sequence (e.g., 1, 2, 3, 4...).
2316
 *
2317
 * 2. For each column that needs to be read (identified by _predicate_column_ids):
2318
 *    - If the rowids are continuous, the function uses seek_to_ordinal and next_batch
2319
 *      for efficient reading.
2320
 *    - If the rowids are not continuous, the function processes them in smaller batches
2321
 *      (each of size up to 256). Each batch is checked for internal continuity:
2322
 *        a. If a batch is continuous, uses seek_to_ordinal and next_batch for that batch.
2323
 *        b. If a batch is not continuous, uses read_by_rowids for individual rowids in the batch.
2324
 *
2325
 * This approach optimizes reading performance by leveraging batch processing for continuous
2326
 * rowid sequences and handling discontinuities gracefully in smaller chunks.
2327
 */
2328
18.0k
Status SegmentIterator::_read_columns_by_index(uint32_t nrows_read_limit, uint16_t& nrows_read) {
2329
18.0k
    SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_ns);
2330
2331
18.0k
    nrows_read = (uint16_t)_range_iter->read_batch_rowids(_block_rowids.data(), nrows_read_limit);
2332
18.0k
    bool is_continuous = (nrows_read > 1) &&
2333
18.0k
                         (_block_rowids[nrows_read - 1] - _block_rowids[0] == nrows_read - 1);
2334
18.0k
    VLOG_DEBUG << fmt::format(
2335
0
            "nrows_read from range iterator: {}, is_continus {}, "
2336
0
            "_cols_read_by_column_predicate "
2337
0
            "[{}]",
2338
0
            nrows_read, is_continuous, fmt::join(_predicate_column_ids, ","));
2339
2340
18.0k
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
2341
0
            "[verbose] SegmentIterator::_read_columns_by_index read {} rowids, continuous: {}, "
2342
0
            "rowids: [{}...{}]",
2343
0
            nrows_read, is_continuous, nrows_read > 0 ? _block_rowids[0] : 0,
2344
0
            nrows_read > 0 ? _block_rowids[nrows_read - 1] : 0);
2345
35.0k
    for (auto cid : _predicate_column_ids) {
2346
35.0k
        auto& column = _current_return_columns[cid];
2347
35.0k
        VLOG_DEBUG << fmt::format("Reading column {}, col_name {}", cid,
2348
0
                                  _schema->column(cid)->name());
2349
35.0k
        if (!_virtual_column_exprs.contains(cid)) {
2350
35.0k
            if (_no_need_read_key_data(cid, column, nrows_read)) {
2351
0
                VLOG_DEBUG << fmt::format("Column {} no need to read.", cid);
2352
0
                continue;
2353
0
            }
2354
35.0k
            if (_prune_column(cid, column, nrows_read)) {
2355
38
                VLOG_DEBUG << fmt::format("Column {} is pruned. No need to read data.", cid);
2356
38
                continue;
2357
38
            }
2358
35.0k
            DBUG_EXECUTE_IF("segment_iterator._read_columns_by_index", {
2359
35.0k
                auto col_name = _opts.tablet_schema->column(cid).name();
2360
35.0k
                auto debug_col_name =
2361
35.0k
                        DebugPoints::instance()->get_debug_param_or_default<std::string>(
2362
35.0k
                                "segment_iterator._read_columns_by_index", "column_name", "");
2363
35.0k
                if (debug_col_name.empty() && col_name != "__DORIS_DELETE_SIGN__") {
2364
35.0k
                    return Status::Error<ErrorCode::INTERNAL_ERROR>(
2365
35.0k
                            "does not need to read data, {}", col_name);
2366
35.0k
                }
2367
35.0k
                if (debug_col_name.find(col_name) != std::string::npos) {
2368
35.0k
                    return Status::Error<ErrorCode::INTERNAL_ERROR>(
2369
35.0k
                            "does not need to read data, {}", col_name);
2370
35.0k
                }
2371
35.0k
            })
2372
35.0k
        }
2373
2374
35.0k
        auto* column_iter = _column_iterators[cid].get();
2375
35.0k
        ScopedColumnIteratorReadPhase scoped_read_phase {
2376
35.0k
                column_iter, _support_lazy_read_pruned_columns.contains(cid)
2377
35.0k
                                     ? ColumnIterator::ReadPhase::PREDICATE
2378
35.0k
                                     : ColumnIterator::ReadPhase::NORMAL};
2379
2380
35.0k
        if (is_continuous) {
2381
26.2k
            size_t rows_read = nrows_read;
2382
26.2k
            _opts.stats->predicate_column_read_seek_num += 1;
2383
26.2k
            if (_opts.runtime_state && _opts.runtime_state->enable_profile()) {
2384
0
                SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_seek_ns);
2385
0
                RETURN_IF_ERROR(column_iter->seek_to_ordinal(_block_rowids[0]));
2386
26.2k
            } else {
2387
26.2k
                RETURN_IF_ERROR(column_iter->seek_to_ordinal(_block_rowids[0]));
2388
26.2k
            }
2389
26.2k
            RETURN_IF_ERROR(column_iter->next_batch(&rows_read, column));
2390
26.2k
            if (rows_read != nrows_read) {
2391
0
                return Status::Error<ErrorCode::INTERNAL_ERROR>("nrows({}) != rows_read({})",
2392
0
                                                                nrows_read, rows_read);
2393
0
            }
2394
26.2k
        } else {
2395
8.78k
            const uint32_t batch_size = _range_iter->get_batch_size();
2396
8.78k
            uint32_t processed = 0;
2397
10.1k
            while (processed < nrows_read) {
2398
1.34k
                uint32_t current_batch_size = std::min(batch_size, nrows_read - processed);
2399
1.34k
                bool batch_continuous = (current_batch_size > 1) &&
2400
1.34k
                                        (_block_rowids[processed + current_batch_size - 1] -
2401
1.21k
                                                 _block_rowids[processed] ==
2402
1.21k
                                         current_batch_size - 1);
2403
2404
1.34k
                if (batch_continuous) {
2405
0
                    size_t rows_read = current_batch_size;
2406
0
                    _opts.stats->predicate_column_read_seek_num += 1;
2407
0
                    if (_opts.runtime_state && _opts.runtime_state->enable_profile()) {
2408
0
                        SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_seek_ns);
2409
0
                        RETURN_IF_ERROR(column_iter->seek_to_ordinal(_block_rowids[processed]));
2410
0
                    } else {
2411
0
                        RETURN_IF_ERROR(column_iter->seek_to_ordinal(_block_rowids[processed]));
2412
0
                    }
2413
0
                    RETURN_IF_ERROR(column_iter->next_batch(&rows_read, column));
2414
0
                    if (rows_read != current_batch_size) {
2415
0
                        return Status::Error<ErrorCode::INTERNAL_ERROR>(
2416
0
                                "batch nrows({}) != rows_read({})", current_batch_size, rows_read);
2417
0
                    }
2418
1.34k
                } else {
2419
1.34k
                    RETURN_IF_ERROR(column_iter->read_by_rowids(&_block_rowids[processed],
2420
1.34k
                                                                current_batch_size, column));
2421
1.34k
                }
2422
1.34k
                processed += current_batch_size;
2423
1.34k
            }
2424
8.78k
        }
2425
35.0k
    }
2426
2427
18.0k
    return Status::OK();
2428
18.0k
}
2429
void SegmentIterator::_replace_version_col_if_needed(const std::vector<ColumnId>& column_ids,
2430
19.4k
                                                     size_t num_rows) {
2431
    // Only the rowset with single version need to replace the version column.
2432
    // Doris can't determine the version before publish_version finished, so
2433
    // we can't write data to __DORIS_VERSION_COL__ in segment writer, the value
2434
    // is 0 by default.
2435
    // So we need to replace the value to real version while reading.
2436
19.4k
    if (_opts.version.first != _opts.version.second) {
2437
6.66k
        return;
2438
6.66k
    }
2439
12.8k
    int32_t version_idx = _schema->version_col_idx();
2440
12.8k
    if (std::ranges::find(column_ids, version_idx) == column_ids.end()) {
2441
12.7k
        return;
2442
12.7k
    }
2443
2444
64
    const auto* column_desc = _schema->column(version_idx);
2445
64
    auto column = Schema::get_data_type_ptr(*column_desc)->create_column();
2446
64
    DCHECK(_schema->column(version_idx)->type() == FieldType::OLAP_FIELD_TYPE_BIGINT);
2447
64
    auto* col_ptr = assert_cast<ColumnInt64*>(column.get());
2448
160
    for (size_t j = 0; j < num_rows; j++) {
2449
96
        col_ptr->insert_value(_opts.version.second);
2450
96
    }
2451
64
    _current_return_columns[version_idx] = std::move(column);
2452
64
    VLOG_DEBUG << "replaced version column in segment iterator, version_col_idx:" << version_idx;
2453
64
}
2454
2455
void SegmentIterator::_update_tso_col_if_needed(const std::vector<ColumnId>& column_ids,
2456
19.4k
                                                size_t num_rows) {
2457
    // use physical time part of commit tso to replace timestamp col
2458
19.4k
    if (_opts.version.first != _opts.version.second) {
2459
6.66k
        return;
2460
6.66k
    }
2461
2462
12.8k
    if (!_opts.read_row_binlog) {
2463
12.8k
        return;
2464
12.8k
    }
2465
2466
0
    int32_t tso_col_idx = _schema->tso_col_idx();
2467
0
    if (tso_col_idx < 0 || std::ranges::find(column_ids, tso_col_idx) == column_ids.end()) {
2468
0
        return;
2469
0
    }
2470
2471
0
    DCHECK_EQ(_opts.commit_tso.start_tso(), _opts.commit_tso.end_tso());
2472
0
    Int64 commit_tso = _opts.commit_tso.end_tso() == -1 ? 0 : _opts.commit_tso.end_tso();
2473
2474
0
    if (_is_pred_column[tso_col_idx]) {
2475
        // Nullable predicate column is represented as ColumnNullable(predicate_col)
2476
0
        if (auto* tso_nullable = check_and_get_column<ColumnNullable>(
2477
0
                    _current_return_columns[tso_col_idx].get())) {
2478
0
            _current_return_columns[tso_col_idx]->clear();
2479
0
            auto value = commit_tso;
2480
0
            for (size_t j = 0; j < num_rows; j++) {
2481
0
                tso_nullable->get_nested_column_ptr()->insert_data(
2482
0
                        reinterpret_cast<const char*>(&value), 0);
2483
0
                tso_nullable->get_null_map_data().emplace_back(0);
2484
0
            }
2485
0
            return;
2486
0
        }
2487
2488
0
        auto* tso_column = assert_cast<ColumnInt64*>(_current_return_columns[tso_col_idx].get());
2489
0
        tso_column->clear();
2490
0
        auto value = commit_tso;
2491
0
        for (size_t j = 0; j < num_rows; j++) {
2492
0
            tso_column->insert_data(reinterpret_cast<const char*>(&value), 0);
2493
0
        }
2494
0
        return;
2495
0
    }
2496
2497
0
    const auto* column_desc = _schema->column(tso_col_idx);
2498
0
    auto column = Schema::get_data_type_ptr(*column_desc)->create_column();
2499
0
    DCHECK(column_desc->type() == FieldType::OLAP_FIELD_TYPE_BIGINT);
2500
2501
0
    if (auto* tso_nullable = check_and_get_column<ColumnNullable>(column.get())) {
2502
0
        auto* col_ptr = assert_cast<ColumnInt64*>(&tso_nullable->get_nested_column());
2503
0
        for (size_t j = 0; j < num_rows; j++) {
2504
0
            col_ptr->insert_value(commit_tso);
2505
0
            tso_nullable->get_null_map_data().emplace_back(0);
2506
0
        }
2507
0
    } else {
2508
0
        auto* col_ptr = assert_cast<ColumnInt64*>(column.get());
2509
0
        for (size_t j = 0; j < num_rows; j++) {
2510
0
            col_ptr->insert_value(commit_tso);
2511
0
        }
2512
0
    }
2513
0
    _current_return_columns[tso_col_idx] = std::move(column);
2514
0
}
2515
2516
uint16_t SegmentIterator::_evaluate_vectorization_predicate(uint16_t* sel_rowid_idx,
2517
1.72k
                                                            uint16_t selected_size) {
2518
1.72k
    SCOPED_RAW_TIMER(&_opts.stats->vec_cond_ns);
2519
1.72k
    bool all_pred_always_true = true;
2520
1.72k
    for (const auto& pred : _pre_eval_block_predicate) {
2521
28
        if (!pred->always_true()) {
2522
28
            all_pred_always_true = false;
2523
28
        } else {
2524
0
            pred->update_filter_info(0, 0, selected_size);
2525
0
        }
2526
28
    }
2527
2528
1.72k
    const uint16_t original_size = selected_size;
2529
    //If all predicates are always_true, then return directly.
2530
1.72k
    if (all_pred_always_true || !_is_need_vec_eval) {
2531
3.90M
        for (uint16_t i = 0; i < original_size; ++i) {
2532
3.90M
            sel_rowid_idx[i] = i;
2533
3.90M
        }
2534
        // All preds are always_true, so return immediately and update the profile statistics here.
2535
1.69k
        _opts.stats->vec_cond_input_rows += original_size;
2536
1.69k
        return original_size;
2537
1.69k
    }
2538
2539
28
    _ret_flags.resize(original_size);
2540
28
    DCHECK(!_pre_eval_block_predicate.empty());
2541
28
    bool is_first = true;
2542
28
    for (auto& pred : _pre_eval_block_predicate) {
2543
28
        if (pred->always_true()) {
2544
0
            continue;
2545
0
        }
2546
28
        auto column_id = pred->column_id();
2547
28
        auto& column = _current_return_columns[column_id];
2548
28
        if (is_first) {
2549
28
            pred->evaluate_vec(*column, original_size, (bool*)_ret_flags.data());
2550
28
            is_first = false;
2551
28
        } else {
2552
0
            pred->evaluate_and_vec(*column, original_size, (bool*)_ret_flags.data());
2553
0
        }
2554
28
    }
2555
2556
28
    uint16_t new_size = 0;
2557
2558
28
    uint16_t sel_pos = 0;
2559
28
    const uint16_t sel_end = sel_pos + selected_size;
2560
28
    static constexpr size_t SIMD_BYTES = simd::bits_mask_length();
2561
28
    const uint16_t sel_end_simd = sel_pos + selected_size / SIMD_BYTES * SIMD_BYTES;
2562
2563
540
    while (sel_pos < sel_end_simd) {
2564
512
        auto mask = simd::bytes_mask_to_bits_mask(_ret_flags.data() + sel_pos);
2565
512
        if (0 == mask) {
2566
            //pass
2567
256
        } else if (simd::bits_mask_all() == mask) {
2568
8.44k
            for (uint16_t i = 0; i < SIMD_BYTES; i++) {
2569
8.19k
                sel_rowid_idx[new_size++] = sel_pos + i;
2570
8.19k
            }
2571
256
        } else {
2572
0
            simd::iterate_through_bits_mask(
2573
0
                    [&](const int bit_pos) {
2574
0
                        sel_rowid_idx[new_size++] = sel_pos + (uint16_t)bit_pos;
2575
0
                    },
2576
0
                    mask);
2577
0
        }
2578
512
        sel_pos += SIMD_BYTES;
2579
512
    }
2580
2581
55
    for (; sel_pos < sel_end; sel_pos++) {
2582
27
        if (_ret_flags[sel_pos]) {
2583
20
            sel_rowid_idx[new_size++] = sel_pos;
2584
20
        }
2585
27
    }
2586
2587
28
    _opts.stats->vec_cond_input_rows += original_size;
2588
28
    _opts.stats->rows_vec_cond_filtered += original_size - new_size;
2589
28
    return new_size;
2590
1.72k
}
2591
2592
uint16_t SegmentIterator::_evaluate_short_circuit_predicate(uint16_t* vec_sel_rowid_idx,
2593
1.72k
                                                            uint16_t selected_size) {
2594
1.72k
    SCOPED_RAW_TIMER(&_opts.stats->short_cond_ns);
2595
1.72k
    if (!_is_need_short_eval) {
2596
28
        return selected_size;
2597
28
    }
2598
2599
1.69k
    uint16_t original_size = selected_size;
2600
1.69k
    for (auto predicate : _short_cir_eval_predicate) {
2601
0
        auto column_id = predicate->column_id();
2602
0
        auto& short_cir_column = _current_return_columns[column_id];
2603
0
        selected_size = predicate->evaluate(*short_cir_column, vec_sel_rowid_idx, selected_size);
2604
0
    }
2605
2606
1.69k
    _opts.stats->short_circuit_cond_input_rows += original_size;
2607
1.69k
    _opts.stats->rows_short_circuit_cond_filtered += original_size - selected_size;
2608
2609
    // evaluate delete condition
2610
1.69k
    original_size = selected_size;
2611
1.69k
    selected_size = _opts.delete_condition_predicates->evaluate(_current_return_columns,
2612
1.69k
                                                                vec_sel_rowid_idx, selected_size);
2613
1.69k
    _opts.stats->rows_vec_del_cond_filtered += original_size - selected_size;
2614
1.69k
    return selected_size;
2615
1.72k
}
2616
2617
1
static void shrink_materialized_block_columns(Block* block, size_t rows) {
2618
2
    for (auto& entry : *block) {
2619
2
        if (entry.column && entry.column->size() > rows) {
2620
1
            entry.column = entry.column->shrink(rows);
2621
1
        }
2622
2
    }
2623
1
}
2624
2625
static void slice_materialized_block_columns(Block* block, size_t offset, size_t rows,
2626
1
                                             size_t original_rows) {
2627
1
    for (auto& entry : *block) {
2628
1
        if (!entry.column || entry.column->size() == 0) {
2629
0
            continue;
2630
0
        }
2631
1
        DORIS_CHECK(entry.column->size() == original_rows);
2632
1
        entry.column = entry.column->cut(offset, rows);
2633
1
    }
2634
1
}
2635
2636
1.73k
Status SegmentIterator::_apply_read_limit_to_selected_rows(Block* block, uint16_t& selected_size) {
2637
1.73k
    if (_opts.read_limit == 0) {
2638
1.73k
        return Status::OK();
2639
1.73k
    }
2640
2
    DORIS_CHECK(_rows_returned <= _opts.read_limit);
2641
2
    size_t remaining = _opts.read_limit - _rows_returned;
2642
2
    if (remaining == 0) {
2643
0
        selected_size = 0;
2644
0
        shrink_materialized_block_columns(block, 0);
2645
0
        return Status::OK();
2646
0
    }
2647
2
    if (selected_size > remaining) {
2648
2
        if (_opts.read_orderby_key_reverse) {
2649
1
            const auto original_size = selected_size;
2650
1
            const auto offset = original_size - remaining;
2651
21
            for (size_t i = 0; i < remaining; ++i) {
2652
20
                _sel_rowid_idx[i] = _sel_rowid_idx[offset + i];
2653
20
            }
2654
1
            selected_size = cast_set<uint16_t>(remaining);
2655
1
            slice_materialized_block_columns(block, offset, remaining, original_size);
2656
1
            return Status::OK();
2657
1
        }
2658
1
        selected_size = cast_set<uint16_t>(remaining);
2659
1
        shrink_materialized_block_columns(block, selected_size);
2660
1
    }
2661
1
    return Status::OK();
2662
2
}
2663
2664
Status SegmentIterator::_read_columns_by_rowids(std::vector<ColumnId>& read_column_ids,
2665
                                                std::vector<rowid_t>& rowid_vector,
2666
                                                uint16_t* sel_rowid_idx, size_t select_size,
2667
                                                MutableColumns* mutable_columns,
2668
                                                bool init_condition_cache,
2669
1.40k
                                                bool read_for_predicate) {
2670
1.40k
    SCOPED_RAW_TIMER(&_opts.stats->lazy_read_ns);
2671
1.40k
    std::vector<rowid_t> rowids(select_size);
2672
2673
1.40k
    if (init_condition_cache) {
2674
0
        DCHECK(_condition_cache);
2675
0
        auto& condition_cache = *_condition_cache;
2676
0
        for (size_t i = 0; i < select_size; ++i) {
2677
0
            rowids[i] = rowid_vector[sel_rowid_idx[i]];
2678
0
            condition_cache[rowids[i] / SegmentIterator::CONDITION_CACHE_OFFSET] = true;
2679
0
        }
2680
1.40k
    } else {
2681
2.75M
        for (size_t i = 0; i < select_size; ++i) {
2682
2.74M
            rowids[i] = rowid_vector[sel_rowid_idx[i]];
2683
2.74M
        }
2684
1.40k
    }
2685
2686
2.12k
    for (auto cid : read_column_ids) {
2687
2.12k
        auto& colunm = (*mutable_columns)[cid];
2688
2.12k
        if (_no_need_read_key_data(cid, colunm, select_size)) {
2689
0
            continue;
2690
0
        }
2691
2.12k
        if (_prune_column(cid, colunm, select_size)) {
2692
0
            continue;
2693
0
        }
2694
2695
2.12k
        DBUG_EXECUTE_IF("segment_iterator._read_columns_by_index", {
2696
2.12k
            auto debug_col_name = DebugPoints::instance()->get_debug_param_or_default<std::string>(
2697
2.12k
                    "segment_iterator._read_columns_by_index", "column_name", "");
2698
2.12k
            if (debug_col_name.empty()) {
2699
2.12k
                return Status::Error<ErrorCode::INTERNAL_ERROR>("does not need to read data");
2700
2.12k
            }
2701
2.12k
            auto col_name = _opts.tablet_schema->column(cid).name();
2702
2.12k
            if (debug_col_name.find(col_name) != std::string::npos) {
2703
2.12k
                return Status::Error<ErrorCode::INTERNAL_ERROR>("does not need to read data, {}",
2704
2.12k
                                                                debug_col_name);
2705
2.12k
            }
2706
2.12k
        })
2707
2708
2.12k
        if (_current_return_columns[cid].get() == nullptr) {
2709
0
            return Status::InternalError(
2710
0
                    "SegmentIterator meet invalid column, return columns size {}, cid {}",
2711
0
                    _current_return_columns.size(), cid);
2712
0
        }
2713
2714
2.12k
        auto* column_iter = _column_iterators[cid].get();
2715
2.12k
        ScopedColumnIteratorReadPhase scoped_read_phase {
2716
2.12k
                column_iter, read_for_predicate && _support_lazy_read_pruned_columns.contains(cid)
2717
2.12k
                                     ? ColumnIterator::ReadPhase::PREDICATE
2718
2.12k
                                     : ColumnIterator::ReadPhase::NORMAL};
2719
2720
2.12k
        RETURN_IF_ERROR(column_iter->read_by_rowids(rowids.data(), select_size,
2721
2.12k
                                                    _current_return_columns[cid]));
2722
2.12k
    }
2723
2724
1.40k
    return Status::OK();
2725
1.40k
}
2726
2727
1.73k
Status SegmentIterator::_read_lazy_pruned_columns(Block* block) {
2728
1.73k
    if (_support_lazy_read_pruned_columns.empty()) {
2729
1.73k
        return Status::OK();
2730
1.73k
    }
2731
2732
2
    SCOPED_RAW_TIMER(&_opts.stats->lazy_read_pruned_ns);
2733
2
    DorisVector<rowid_t> rowids(_selected_size);
2734
4
    for (size_t i = 0; i < _selected_size; ++i) {
2735
2
        rowids[i] = _block_rowids[_sel_rowid_idx[i]];
2736
2
    }
2737
2738
2
    for (auto cid : _support_lazy_read_pruned_columns) {
2739
2
        auto loc = _schema->column_index(cid);
2740
2
        auto column = IColumn::mutate(std::move(block->get_by_position(loc).column));
2741
2
        auto* column_iter = _column_iterators[cid].get();
2742
2
        ScopedColumnIteratorReadPhase scoped_read_phase {column_iter,
2743
2
                                                         ColumnIterator::ReadPhase::LAZY};
2744
2
        if (_selected_size > 0) {
2745
1
            RETURN_IF_ERROR(column_iter->read_by_rowids(rowids.data(), _selected_size, column));
2746
1
        }
2747
2
        column_iter->finalize_lazy_phase(column);
2748
2
        block->get_by_position(loc).column = std::move(column);
2749
2
    }
2750
2
    return Status::OK();
2751
2
}
2752
2753
18.0k
Status SegmentIterator::next_batch(Block* block) {
2754
    // Replace virtual columns with ColumnNothing at the begining of each next_batch call.
2755
18.0k
    _init_virtual_columns(block);
2756
18.0k
    auto status = [&]() {
2757
18.0k
        RETURN_IF_CATCH_EXCEPTION({
2758
            // Adaptive batch size: predict how many rows this batch should read.
2759
18.0k
            if (_block_size_predictor) {
2760
18.0k
                auto predicted = static_cast<uint32_t>(_block_size_predictor->predict_next_rows());
2761
18.0k
                _opts.block_row_max = std::min(predicted, _initial_block_row_max);
2762
18.0k
                _opts.stats->adaptive_batch_size_predict_min_rows =
2763
18.0k
                        std::min(_opts.stats->adaptive_batch_size_predict_min_rows,
2764
18.0k
                                 static_cast<int64_t>(predicted));
2765
18.0k
                _opts.stats->adaptive_batch_size_predict_max_rows =
2766
18.0k
                        std::max(_opts.stats->adaptive_batch_size_predict_max_rows,
2767
18.0k
                                 static_cast<int64_t>(predicted));
2768
18.0k
            } else {
2769
                // No predictor — record the fixed batch size using min/max so we don't
2770
                // clobber values already accumulated by other segment iterators that
2771
                // share the same OlapReaderStatistics.
2772
18.0k
                _opts.stats->adaptive_batch_size_predict_min_rows =
2773
18.0k
                        std::min(_opts.stats->adaptive_batch_size_predict_min_rows,
2774
18.0k
                                 static_cast<int64_t>(_opts.block_row_max));
2775
18.0k
                _opts.stats->adaptive_batch_size_predict_max_rows =
2776
18.0k
                        std::max(_opts.stats->adaptive_batch_size_predict_max_rows,
2777
18.0k
                                 static_cast<int64_t>(_opts.block_row_max));
2778
18.0k
            }
2779
2780
18.0k
            auto res = _next_batch_internal(block);
2781
2782
18.0k
            if (res.is<END_OF_FILE>()) {
2783
                // Since we have a type check at the caller.
2784
                // So a replacement of nothing column with real column is needed.
2785
18.0k
                for (const auto& [cid, expr_ctx] : _virtual_column_exprs) {
2786
18.0k
                    auto idx = _schema->column_index(cid);
2787
18.0k
                    auto type = expr_ctx->root()->data_type();
2788
18.0k
                    block->replace_by_position(idx, type->create_column());
2789
18.0k
                }
2790
2791
18.0k
                if (_opts.condition_cache_digest && !_find_condition_cache) {
2792
18.0k
                    auto* condition_cache = ConditionCache::instance();
2793
18.0k
                    ConditionCache::CacheKey cache_key(_opts.rowset_id, _segment->id(),
2794
18.0k
                                                       _opts.condition_cache_digest);
2795
18.0k
                    VLOG_DEBUG << "Condition cache insert, query id: "
2796
18.0k
                               << print_id(_opts.runtime_state->query_id())
2797
18.0k
                               << ", rowset id: " << _opts.rowset_id.to_string()
2798
18.0k
                               << ", segment id: " << _segment->id()
2799
18.0k
                               << ", cache digest: " << _opts.condition_cache_digest;
2800
18.0k
                    condition_cache->insert(cache_key, std::move(_condition_cache));
2801
18.0k
                }
2802
18.0k
                return res;
2803
18.0k
            }
2804
2805
18.0k
            RETURN_IF_ERROR(res);
2806
            // reverse block row order if read_orderby_key_reverse is true for key topn
2807
            // it should be processed for all success _next_batch_internal
2808
18.0k
            if (_opts.read_orderby_key_reverse) {
2809
18.0k
                size_t num_rows = block->rows();
2810
18.0k
                if (num_rows == 0) {
2811
18.0k
                    return Status::OK();
2812
18.0k
                }
2813
18.0k
                size_t num_columns = block->columns();
2814
18.0k
                IColumn::Permutation permutation;
2815
18.0k
                for (size_t i = 0; i < num_rows; ++i) permutation.emplace_back(num_rows - 1 - i);
2816
2817
18.0k
                for (size_t i = 0; i < num_columns; ++i)
2818
18.0k
                    block->get_by_position(i).column =
2819
18.0k
                            block->get_by_position(i).column->permute(permutation, num_rows);
2820
18.0k
            }
2821
2822
18.0k
            RETURN_IF_ERROR(block->check_type_and_column());
2823
2824
            // Adaptive batch size: update EWMA estimate from the completed batch.
2825
            // block->bytes() is accurate here: predicates have been applied and non-predicate
2826
            // columns have been filled for surviving rows by _next_batch_internal.
2827
18.0k
            if (_block_size_predictor && block->rows() > 0) {
2828
18.0k
                _block_size_predictor->update(*block);
2829
18.0k
            }
2830
2831
18.0k
            return Status::OK();
2832
18.0k
        });
2833
18.0k
    }();
2834
2835
    // if rows read by batch is 0, will return end of file, we should not remove segment cache in this situation.
2836
18.0k
    if (!status.ok() && !status.is<END_OF_FILE>()) {
2837
0
        _segment->update_healthy_status(status);
2838
0
    }
2839
18.0k
    return status;
2840
18.0k
}
2841
2842
18.0k
Status SegmentIterator::_convert_to_expected_type(const std::vector<ColumnId>& col_ids) {
2843
36.1k
    for (ColumnId i : col_ids) {
2844
36.1k
        if (!_current_return_columns[i] || _converted_column_ids[i] || _is_pred_column[i]) {
2845
410
            continue;
2846
410
        }
2847
35.7k
        const TabletColumn* column_desc = _schema->column(i);
2848
35.7k
        DataTypePtr expected_type = Schema::get_data_type_ptr(*column_desc);
2849
35.7k
        DataTypePtr file_column_type = _storage_name_and_type[i].second;
2850
35.7k
        if (!file_column_type->equals(*expected_type)) {
2851
50
            ColumnPtr expected;
2852
50
            ColumnPtr original = _current_return_columns[i]->assert_mutable()->get_ptr();
2853
50
            RETURN_IF_ERROR(variant_util::cast_column({original, file_column_type, ""},
2854
50
                                                      expected_type, &expected));
2855
50
            _current_return_columns[i] = expected->assert_mutable();
2856
50
            _converted_column_ids[i] = true;
2857
50
            VLOG_DEBUG << fmt::format("Convert {} fom file column type {} to {}, num_rows {}",
2858
0
                                      column_desc->path_info_ptr() == nullptr
2859
0
                                              ? ""
2860
0
                                              : column_desc->path_info_ptr()->get_path(),
2861
0
                                      file_column_type->get_name(), expected_type->get_name(),
2862
0
                                      _current_return_columns[i]->size());
2863
50
        }
2864
35.7k
    }
2865
18.0k
    return Status::OK();
2866
18.0k
}
2867
2868
Status SegmentIterator::copy_column_data_by_selector(IColumn* input_col_ptr,
2869
                                                     MutableColumnPtr& output_col,
2870
                                                     uint16_t* sel_rowid_idx, uint16_t select_size,
2871
1.41k
                                                     size_t batch_size) {
2872
1.41k
    if (is_column_nullable(*output_col) != is_column_nullable(*input_col_ptr)) {
2873
0
        LOG(WARNING) << "nullable mismatch for output_column: " << output_col->dump_structure()
2874
0
                     << " input_column: " << input_col_ptr->dump_structure()
2875
0
                     << " select_size: " << select_size;
2876
0
        return Status::RuntimeError("copy_column_data_by_selector nullable mismatch");
2877
0
    }
2878
1.41k
    output_col->reserve(select_size);
2879
1.41k
    return input_col_ptr->filter_by_selector(sel_rowid_idx, select_size, output_col.get());
2880
1.41k
}
2881
2882
18.0k
Status SegmentIterator::_next_batch_internal(Block* block) {
2883
18.0k
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().segment_iterator_next_batch);
2884
2885
18.0k
    bool is_mem_reuse = block->mem_reuse();
2886
18.0k
    DCHECK(is_mem_reuse);
2887
2888
18.0k
    RETURN_IF_ERROR(_lazy_init(block));
2889
2890
18.0k
    SCOPED_RAW_TIMER(&_opts.stats->block_load_ns);
2891
2892
18.0k
    if (_opts.read_limit > 0 && _rows_returned >= _opts.read_limit) {
2893
0
        return _process_eof(block);
2894
0
    }
2895
2896
    // If the row bitmap size is smaller than nrows_read_limit, there's no need to reserve that many column rows.
2897
18.0k
    uint32_t nrows_read_limit =
2898
18.0k
            std::min(cast_set<uint32_t>(_row_bitmap.cardinality()), _opts.block_row_max);
2899
18.0k
    if (_can_opt_limit_reads()) {
2900
        // No SegmentIterator-side conjunct remains to be evaluated, so LIMIT is equivalent before
2901
        // and after filtering. Cap the first read directly; this is the no-conjunct fast path that
2902
        // avoids reading rows past the pushed-down local LIMIT.
2903
0
        size_t cap = (_opts.read_limit > _rows_returned) ? (_opts.read_limit - _rows_returned) : 0;
2904
0
        if (cap < nrows_read_limit) {
2905
0
            nrows_read_limit = static_cast<uint32_t>(cap);
2906
0
        }
2907
0
    }
2908
18.0k
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_1", {
2909
18.0k
        if (nrows_read_limit != 1) {
2910
18.0k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
2911
18.0k
                    "topn opt 1 execute failed: nrows_read_limit={}, "
2912
18.0k
                    "_opts.read_limit={}",
2913
18.0k
                    nrows_read_limit, _opts.read_limit);
2914
18.0k
        }
2915
18.0k
    })
2916
2917
18.0k
    RETURN_IF_ERROR(_init_current_block(block, _current_return_columns, nrows_read_limit));
2918
18.0k
    _converted_column_ids.assign(_schema->columns().size(), false);
2919
2920
18.0k
    _selected_size = 0;
2921
18.0k
    RETURN_IF_ERROR(_read_columns_by_index(nrows_read_limit, _selected_size));
2922
18.0k
    _replace_version_col_if_needed(_predicate_column_ids, _selected_size);
2923
18.0k
    _update_tso_col_if_needed(_predicate_column_ids, _selected_size);
2924
2925
18.0k
    _opts.stats->blocks_load += 1;
2926
18.0k
    _opts.stats->raw_rows_read += _selected_size;
2927
2928
18.0k
    if (_selected_size == 0) {
2929
3.49k
        return _process_eof(block);
2930
3.49k
    }
2931
2932
14.5k
    if (_is_need_vec_eval || _is_need_short_eval || _is_need_expr_eval) {
2933
1.73k
        _sel_rowid_idx.resize(_selected_size);
2934
2935
1.73k
        if (_is_need_vec_eval || _is_need_short_eval) {
2936
1.72k
            _convert_dict_code_for_predicate_if_necessary();
2937
2938
            // step 1: evaluate vectorization predicate
2939
1.72k
            _selected_size =
2940
1.72k
                    _evaluate_vectorization_predicate(_sel_rowid_idx.data(), _selected_size);
2941
2942
            // step 2: evaluate short circuit predicate
2943
            // todo(wb) research whether need to read short predicate after vectorization evaluation
2944
            //          to reduce cost of read short circuit columns.
2945
            //          In SSB test, it make no difference; So need more scenarios to test
2946
1.72k
            _selected_size =
2947
1.72k
                    _evaluate_short_circuit_predicate(_sel_rowid_idx.data(), _selected_size);
2948
1.72k
            VLOG_DEBUG << fmt::format("After evaluate predicates, selected size: {} ",
2949
0
                                      _selected_size);
2950
1.72k
            if (_selected_size > 0) {
2951
                // step 3.1: output short circuit and predicate column
2952
                // when lazy materialization enables, _predicate_column_ids = distinct(_short_cir_pred_column_ids + _vec_pred_column_ids)
2953
                // see _vec_init_lazy_materialization
2954
                // todo(wb) need to tell input columnids from output columnids
2955
1.68k
                RETURN_IF_ERROR(_output_column_by_sel_idx(block, _predicate_column_ids,
2956
1.68k
                                                          _sel_rowid_idx.data(), _selected_size));
2957
2958
                // step 3.2: read remaining expr column and evaluate it.
2959
1.68k
                if (_is_need_expr_eval) {
2960
                    // The predicate column contains the remaining expr column, no need second read.
2961
0
                    if (_common_expr_column_ids.size() > 0) {
2962
0
                        SCOPED_RAW_TIMER(&_opts.stats->non_predicate_read_ns);
2963
0
                        RETURN_IF_ERROR(_read_columns_by_rowids(
2964
0
                                _common_expr_column_ids, _block_rowids, _sel_rowid_idx.data(),
2965
0
                                _selected_size, &_current_return_columns, false, true));
2966
0
                        _replace_version_col_if_needed(_common_expr_column_ids, _selected_size);
2967
0
                        _update_tso_col_if_needed(_common_expr_column_ids, _selected_size);
2968
0
                        RETURN_IF_ERROR(_process_columns(_common_expr_column_ids, block));
2969
0
                    }
2970
2971
0
                    DCHECK(block->columns() > _schema->column_index(*_common_expr_columns.begin()));
2972
0
                    RETURN_IF_ERROR(
2973
0
                            _process_common_expr(_sel_rowid_idx.data(), _selected_size, block));
2974
0
                }
2975
1.68k
            } else {
2976
38
                _fill_column_nothing();
2977
38
                if (_is_need_expr_eval) {
2978
0
                    RETURN_IF_ERROR(_process_columns(_common_expr_column_ids, block));
2979
0
                }
2980
38
            }
2981
1.72k
        } else if (_is_need_expr_eval) {
2982
6
            DCHECK(!_predicate_column_ids.empty());
2983
6
            RETURN_IF_ERROR(_process_columns(_predicate_column_ids, block));
2984
            // first read all rows are insert block, initialize sel_rowid_idx to all rows.
2985
23
            for (uint16_t i = 0; i < _selected_size; ++i) {
2986
17
                _sel_rowid_idx[i] = i;
2987
17
            }
2988
6
            RETURN_IF_ERROR(_process_common_expr(_sel_rowid_idx.data(), _selected_size, block));
2989
6
        }
2990
2991
1.73k
        RETURN_IF_ERROR(_apply_read_limit_to_selected_rows(block, _selected_size));
2992
2993
        // step4: read non_predicate column
2994
1.73k
        if (_selected_size > 0) {
2995
1.69k
            if (!_non_predicate_columns.empty()) {
2996
1.40k
                RETURN_IF_ERROR(_read_columns_by_rowids(
2997
1.40k
                        _non_predicate_columns, _block_rowids, _sel_rowid_idx.data(),
2998
1.40k
                        _selected_size, &_current_return_columns,
2999
1.40k
                        _opts.condition_cache_digest && !_find_condition_cache, false));
3000
1.40k
                _replace_version_col_if_needed(_non_predicate_columns, _selected_size);
3001
1.40k
                _update_tso_col_if_needed(_non_predicate_columns, _selected_size);
3002
1.40k
            } else {
3003
286
                if (_opts.condition_cache_digest && !_find_condition_cache) {
3004
0
                    auto& condition_cache = *_condition_cache;
3005
0
                    for (size_t i = 0; i < _selected_size; ++i) {
3006
0
                        auto rowid = _block_rowids[_sel_rowid_idx[i]];
3007
0
                        condition_cache[rowid / SegmentIterator::CONDITION_CACHE_OFFSET] = true;
3008
0
                    }
3009
0
                }
3010
286
            }
3011
1.69k
        }
3012
3013
1.73k
        RETURN_IF_ERROR(_read_lazy_pruned_columns(block));
3014
1.73k
    }
3015
3016
    // step5: output columns
3017
14.5k
    RETURN_IF_ERROR(_output_non_pred_columns(block));
3018
    // Convert inverted index bitmaps to result columns for virtual column exprs
3019
    // (e.g., MATCH projections). This must run before _materialization_of_virtual_column
3020
    // so that fast_execute() can find the pre-computed result columns.
3021
14.5k
    if (!_virtual_column_exprs.empty()) {
3022
0
        bool use_sel = _is_need_vec_eval || _is_need_short_eval || _is_need_expr_eval;
3023
0
        uint16_t* sel_rowid_idx = use_sel ? _sel_rowid_idx.data() : nullptr;
3024
0
        VExprContextSPtrs vir_ctxs;
3025
0
        vir_ctxs.reserve(_virtual_column_exprs.size());
3026
0
        for (auto& [cid, ctx] : _virtual_column_exprs) {
3027
0
            vir_ctxs.push_back(ctx);
3028
0
        }
3029
0
        _output_index_result_column(vir_ctxs, sel_rowid_idx, _selected_size);
3030
0
    }
3031
14.5k
    RETURN_IF_ERROR(_materialization_of_virtual_column(block));
3032
14.5k
    if (_opts.read_limit > 0) {
3033
0
        _rows_returned += block->rows();
3034
0
    }
3035
14.5k
    return _check_output_block(block);
3036
14.5k
}
3037
3038
6
Status SegmentIterator::_process_columns(const std::vector<ColumnId>& column_ids, Block* block) {
3039
6
    RETURN_IF_ERROR(_convert_to_expected_type(column_ids));
3040
6
    for (auto cid : column_ids) {
3041
6
        auto loc = _schema->column_index(cid);
3042
6
        block->replace_by_position(loc, std::move(_current_return_columns[cid]));
3043
6
    }
3044
6
    return Status::OK();
3045
6
}
3046
3047
38
void SegmentIterator::_fill_column_nothing() {
3048
    // If column_predicate filters out all rows, the corresponding column in _current_return_columns[cid] must be a ColumnNothing.
3049
    // Because:
3050
    // 1. Before each batch, _init_return_columns is called to initialize _current_return_columns, and virtual columns in _current_return_columns are initialized as ColumnNothing.
3051
    // 2. When select_size == 0, the read method of VirtualColumnIterator will definitely not be called, so the corresponding Column remains a ColumnNothing
3052
38
    for (const auto& [cid, expr_ctx] : _virtual_column_exprs) {
3053
0
        [[maybe_unused]] const auto* nothing_col =
3054
0
                assert_cast<const ColumnNothing*>(_current_return_columns[cid].get());
3055
0
        _current_return_columns[cid] = expr_ctx->root()->data_type()->create_column();
3056
0
    }
3057
38
}
3058
3059
14.5k
Status SegmentIterator::_check_output_block(Block* block) {
3060
14.5k
#ifndef NDEBUG
3061
14.5k
    size_t rows = block->rows();
3062
14.5k
    size_t idx = 0;
3063
28.6k
    for (const auto& entry : *block) {
3064
28.6k
        if (!entry.column) {
3065
0
            return Status::InternalError(
3066
0
                    "Column in idx {} is null, block columns {}, normal_columns {}, "
3067
0
                    "virtual_columns {}",
3068
0
                    idx, block->columns(), _schema->num_column_ids(), _virtual_column_exprs.size());
3069
28.6k
        } else if (check_and_get_column<ColumnNothing>(entry.column.get())) {
3070
0
            if (rows > 0) {
3071
0
                std::vector<ColumnId> virtual_column_ids;
3072
0
                for (const auto& pair : _virtual_column_exprs) {
3073
0
                    virtual_column_ids.push_back(pair.first);
3074
0
                }
3075
0
                return Status::InternalError(
3076
0
                        "Column in idx {} is nothing, block columns {}, normal_columns {}, "
3077
0
                        "virtual_column_ids [{}]",
3078
0
                        idx, block->columns(), _schema->num_column_ids(),
3079
0
                        fmt::join(virtual_column_ids, ","));
3080
0
            }
3081
28.6k
        } else if (entry.column->size() != rows) {
3082
0
            return Status::InternalError(
3083
0
                    "Unmatched size {}, expected {}, column: {}, type: {}, idx_in_block: {}, "
3084
0
                    "block: {}",
3085
0
                    entry.column->size(), rows, entry.column->get_name(), entry.type->get_name(),
3086
0
                    idx, block->dump_structure());
3087
0
        }
3088
28.6k
        idx++;
3089
28.6k
    }
3090
14.5k
#endif
3091
14.5k
    return Status::OK();
3092
14.5k
}
3093
3094
3.49k
Status SegmentIterator::_process_eof(Block* block) {
3095
    // Convert all columns in _current_return_columns to schema column
3096
3.49k
    RETURN_IF_ERROR(_convert_to_expected_type(_schema->column_ids()));
3097
12.3k
    for (int i = 0; i < block->columns(); i++) {
3098
8.87k
        auto cid = _schema->column_id(i);
3099
8.87k
        if (!_is_pred_column[cid]) {
3100
8.59k
            block->replace_by_position(i, std::move(_current_return_columns[cid]));
3101
8.59k
        }
3102
8.87k
    }
3103
3.49k
    block->clear_column_data();
3104
    // clear and release iterators memory footprint in advance
3105
3.49k
    _column_iterators.clear();
3106
3.49k
    _index_iterators.clear();
3107
3.49k
    return Status::EndOfFile("no more data in segment");
3108
3.49k
}
3109
3110
Status SegmentIterator::_process_common_expr(uint16_t* sel_rowid_idx, uint16_t& selected_size,
3111
6
                                             Block* block) {
3112
6
    VLOG_DEBUG << fmt::format("Execute common expr. block rows {}, selected size {}", block->rows(),
3113
0
                              _selected_size);
3114
3115
6
    RETURN_IF_ERROR(_execute_common_expr(sel_rowid_idx, selected_size, block));
3116
3117
6
    VLOG_DEBUG << fmt::format("Execute common expr end. block rows {}, selected size {}",
3118
0
                              block->rows(), _selected_size);
3119
6
    return Status::OK();
3120
6
}
3121
3122
Status SegmentIterator::_execute_common_expr(uint16_t* sel_rowid_idx, uint16_t& selected_size,
3123
6
                                             Block* block) {
3124
6
    SCOPED_RAW_TIMER(&_opts.stats->expr_filter_ns);
3125
6
    DCHECK(!_common_expr_ctxs_push_down.empty());
3126
6
    _output_index_result_column(_common_expr_ctxs_push_down, sel_rowid_idx, selected_size);
3127
3128
6
    uint16_t original_size = selected_size;
3129
6
    _opts.stats->expr_cond_input_rows += original_size;
3130
3131
    // Some output columns may stay empty until after common expr filtering. Use the
3132
    // selected row count instead of Block::rows(), which is derived from the first column.
3133
6
    IColumn::Filter filter(selected_size, 1);
3134
6
    bool can_filter_all = false;
3135
6
    auto* __restrict filter_data = filter.data();
3136
6
    for (const auto& expr_ctx : _common_expr_ctxs_push_down) {
3137
6
        RETURN_IF_ERROR(expr_ctx->execute_filter(block, filter_data, selected_size, false,
3138
6
                                                 &can_filter_all));
3139
6
        if (can_filter_all) {
3140
0
            break;
3141
0
        }
3142
6
    }
3143
6
    RETURN_IF_CATCH_EXCEPTION(Block::filter_block_internal(block, _columns_to_filter, filter));
3144
3145
6
    selected_size = _evaluate_common_expr_filter(sel_rowid_idx, selected_size, filter);
3146
6
    _opts.stats->rows_expr_cond_filtered += original_size - selected_size;
3147
6
    return Status::OK();
3148
6
}
3149
3150
uint16_t SegmentIterator::_evaluate_common_expr_filter(uint16_t* sel_rowid_idx,
3151
                                                       uint16_t selected_size,
3152
6
                                                       const IColumn::Filter& filter) {
3153
6
    size_t count = filter.size() - simd::count_zero_num((int8_t*)filter.data(), filter.size());
3154
6
    if (count == 0) {
3155
0
        return 0;
3156
6
    } else {
3157
6
        const UInt8* filt_pos = filter.data();
3158
3159
6
        uint16_t new_size = 0;
3160
6
        uint32_t sel_pos = 0;
3161
6
        const uint32_t sel_end = selected_size;
3162
6
        static constexpr size_t SIMD_BYTES = simd::bits_mask_length();
3163
6
        const uint32_t sel_end_simd = sel_pos + selected_size / SIMD_BYTES * SIMD_BYTES;
3164
3165
6
        while (sel_pos < sel_end_simd) {
3166
0
            auto mask = simd::bytes_mask_to_bits_mask(filt_pos + sel_pos);
3167
0
            if (0 == mask) {
3168
                //pass
3169
0
            } else if (simd::bits_mask_all() == mask) {
3170
0
                for (uint32_t i = 0; i < SIMD_BYTES; i++) {
3171
0
                    sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos + i];
3172
0
                }
3173
0
            } else {
3174
0
                simd::iterate_through_bits_mask(
3175
0
                        [&](const size_t bit_pos) {
3176
0
                            sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos + bit_pos];
3177
0
                        },
3178
0
                        mask);
3179
0
            }
3180
0
            sel_pos += SIMD_BYTES;
3181
0
        }
3182
3183
23
        for (; sel_pos < sel_end; sel_pos++) {
3184
17
            if (filt_pos[sel_pos]) {
3185
7
                sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos];
3186
7
            }
3187
17
        }
3188
6
        return new_size;
3189
6
    }
3190
6
}
3191
3192
void SegmentIterator::_output_index_result_column(const VExprContextSPtrs& expr_ctxs,
3193
6
                                                  uint16_t* sel_rowid_idx, uint16_t select_size) {
3194
6
    SCOPED_RAW_TIMER(&_opts.stats->output_index_result_column_timer);
3195
6
    if (select_size == 0) {
3196
0
        return;
3197
0
    }
3198
6
    for (const auto& expr_ctx : expr_ctxs) {
3199
6
        auto index_ctx = expr_ctx->get_index_context();
3200
6
        if (index_ctx == nullptr) {
3201
0
            continue;
3202
0
        }
3203
6
        for (auto& inverted_index_result_bitmap_for_expr : index_ctx->get_index_result_bitmap()) {
3204
0
            const auto* expr = inverted_index_result_bitmap_for_expr.first;
3205
0
            const auto& result_bitmap = inverted_index_result_bitmap_for_expr.second;
3206
0
            const auto& index_result_bitmap = result_bitmap.get_data_bitmap();
3207
0
            auto index_result_column = ColumnUInt8::create();
3208
0
            ColumnUInt8::Container& vec_match_pred = index_result_column->get_data();
3209
0
            vec_match_pred.resize(select_size);
3210
0
            std::fill(vec_match_pred.begin(), vec_match_pred.end(), 0);
3211
3212
0
            const auto& null_bitmap = result_bitmap.get_null_bitmap();
3213
0
            bool has_null_bitmap = null_bitmap != nullptr && !null_bitmap->isEmpty();
3214
0
            bool expr_returns_nullable = expr->data_type()->is_nullable();
3215
3216
0
            ColumnUInt8::MutablePtr null_map_column = nullptr;
3217
0
            ColumnUInt8::Container* null_map_data = nullptr;
3218
0
            if (has_null_bitmap && expr_returns_nullable) {
3219
0
                null_map_column = ColumnUInt8::create();
3220
0
                auto& null_map_vec = null_map_column->get_data();
3221
0
                null_map_vec.resize(select_size);
3222
0
                std::fill(null_map_vec.begin(), null_map_vec.end(), 0);
3223
0
                null_map_data = &null_map_column->get_data();
3224
0
            }
3225
3226
0
            roaring::BulkContext bulk_context;
3227
0
            for (uint32_t i = 0; i < select_size; i++) {
3228
0
                auto rowid = sel_rowid_idx ? _block_rowids[sel_rowid_idx[i]] : _block_rowids[i];
3229
0
                if (index_result_bitmap) {
3230
0
                    vec_match_pred[i] = index_result_bitmap->containsBulk(bulk_context, rowid);
3231
0
                }
3232
0
                if (null_map_data != nullptr && null_bitmap->contains(rowid)) {
3233
0
                    (*null_map_data)[i] = 1;
3234
0
                    vec_match_pred[i] = 0;
3235
0
                }
3236
0
            }
3237
3238
0
            DCHECK(select_size == vec_match_pred.size());
3239
3240
0
            if (null_map_column) {
3241
0
                index_ctx->set_index_result_column_for_expr(
3242
0
                        expr, ColumnNullable::create(std::move(index_result_column),
3243
0
                                                     std::move(null_map_column)));
3244
0
            } else {
3245
0
                index_ctx->set_index_result_column_for_expr(expr, std::move(index_result_column));
3246
0
            }
3247
0
        }
3248
6
    }
3249
6
}
3250
3251
1.72k
void SegmentIterator::_convert_dict_code_for_predicate_if_necessary() {
3252
1.72k
    for (auto predicate : _short_cir_eval_predicate) {
3253
0
        _convert_dict_code_for_predicate_if_necessary_impl(predicate);
3254
0
    }
3255
3256
1.72k
    for (auto predicate : _pre_eval_block_predicate) {
3257
28
        _convert_dict_code_for_predicate_if_necessary_impl(predicate);
3258
28
    }
3259
3260
1.72k
    for (auto column_id : _delete_range_column_ids) {
3261
1.55k
        _current_return_columns[column_id].get()->convert_dict_codes_if_necessary();
3262
1.55k
    }
3263
3264
1.72k
    for (auto column_id : _delete_bloom_filter_column_ids) {
3265
0
        _current_return_columns[column_id].get()->initialize_hash_values_for_runtime_filter();
3266
0
    }
3267
1.72k
}
3268
3269
void SegmentIterator::_convert_dict_code_for_predicate_if_necessary_impl(
3270
28
        std::shared_ptr<ColumnPredicate> predicate) {
3271
28
    auto& column = _current_return_columns[predicate->column_id()];
3272
28
    auto* col_ptr = column.get();
3273
3274
28
    if (PredicateTypeTraits::is_range(predicate->type())) {
3275
22
        col_ptr->convert_dict_codes_if_necessary();
3276
22
    } else if (PredicateTypeTraits::is_bloom_filter(predicate->type())) {
3277
0
        col_ptr->initialize_hash_values_for_runtime_filter();
3278
0
    }
3279
28
}
3280
3281
2.93k
Status SegmentIterator::current_block_row_locations(std::vector<RowLocation>* block_row_locations) {
3282
2.93k
    DCHECK(_opts.record_rowids);
3283
2.93k
    DCHECK_GE(_block_rowids.size(), _selected_size);
3284
2.93k
    block_row_locations->resize(_selected_size);
3285
2.93k
    uint32_t sid = segment_id();
3286
2.93k
    if (!_is_need_vec_eval && !_is_need_short_eval && !_is_need_expr_eval) {
3287
4.24M
        for (auto i = 0; i < _selected_size; i++) {
3288
4.23M
            (*block_row_locations)[i] = RowLocation(sid, _block_rowids[i]);
3289
4.23M
        }
3290
1.76k
    } else {
3291
2.46M
        for (auto i = 0; i < _selected_size; i++) {
3292
2.46M
            (*block_row_locations)[i] = RowLocation(sid, _block_rowids[_sel_rowid_idx[i]]);
3293
2.46M
        }
3294
1.16k
    }
3295
2.93k
    return Status::OK();
3296
2.93k
}
3297
3298
4.39k
Status SegmentIterator::_construct_compound_expr_context() {
3299
4.39k
    ColumnIteratorOptions iter_opts {
3300
4.39k
            .use_page_cache = _opts.use_page_cache,
3301
4.39k
            .file_reader = _file_reader.get(),
3302
4.39k
            .stats = _opts.stats,
3303
4.39k
            .io_ctx = _opts.io_ctx,
3304
4.39k
    };
3305
4.39k
    auto inverted_index_context = std::make_shared<IndexExecContext>(
3306
4.39k
            _schema->column_ids(), _index_iterators, _storage_name_and_type,
3307
4.39k
            _common_expr_index_exec_status, _score_runtime, _segment.get(), iter_opts);
3308
4.39k
    inverted_index_context->set_index_query_context(_index_query_context);
3309
4.39k
    for (const auto& expr_ctx : _opts.common_expr_ctxs_push_down) {
3310
21
        VExprContextSPtr context;
3311
        // _ann_range_search_runtime will do deep copy.
3312
21
        RETURN_IF_ERROR(expr_ctx->clone(_opts.runtime_state, context));
3313
21
        context->set_index_context(inverted_index_context);
3314
21
        _common_expr_ctxs_push_down.emplace_back(context);
3315
21
    }
3316
    // Clone virtual column exprs before setting IndexExecContext, because
3317
    // IndexExecContext holds segment-specific index iterator references.
3318
    // Without cloning, shared VExprContext would be overwritten per-segment
3319
    // and could point to the wrong segment's context.
3320
4.39k
    for (auto& [cid, expr_ctx] : _virtual_column_exprs) {
3321
0
        VExprContextSPtr context;
3322
0
        RETURN_IF_ERROR(expr_ctx->clone(_opts.runtime_state, context));
3323
0
        context->set_index_context(inverted_index_context);
3324
0
        expr_ctx = context;
3325
0
    }
3326
4.39k
    return Status::OK();
3327
4.39k
}
3328
3329
Status SegmentIterator::_apply_expr_zonemap_to_row_ranges(const VExprContextSPtrs& conjuncts,
3330
                                                          rowid_t min_rowid,
3331
7
                                                          RowRanges* row_ranges) {
3332
7
    DORIS_CHECK(row_ranges != nullptr);
3333
7
    if (!expr_zonemap::is_expr_zonemap_filter_enabled(_opts.runtime_state) || conjuncts.empty() ||
3334
7
        row_ranges->is_empty()) {
3335
0
        return Status::OK();
3336
0
    }
3337
3338
7
    std::unordered_map<int, VExprContextSPtrs> ctxs_by_slot;
3339
7
    for (const auto& conjunct : conjuncts) {
3340
7
        auto slot_index = expr_zonemap::single_slot_zonemap_index(conjunct);
3341
7
        if (slot_index >= 0) {
3342
5
            ctxs_by_slot[slot_index].emplace_back(conjunct);
3343
5
        }
3344
7
    }
3345
    // Page zone maps are stored per column. Multi-slot expressions need page alignment across
3346
    // multiple column readers and are therefore left to segment-level pruning for now.
3347
7
    if (ctxs_by_slot.empty()) {
3348
2
        return Status::OK();
3349
2
    }
3350
3351
5
    ColumnIteratorOptions iter_opts {
3352
5
            .use_page_cache = _opts.use_page_cache,
3353
5
            .file_reader = _file_reader.get(),
3354
5
            .stats = _opts.stats,
3355
5
            .io_ctx = _opts.io_ctx,
3356
5
    };
3357
5
    for (const auto& [slot_index, slot_conjuncts] : ctxs_by_slot) {
3358
5
        if (cast_set<size_t>(slot_index) >= _schema->num_column_ids()) {
3359
0
            continue;
3360
0
        }
3361
5
        const auto cid = _schema->column_id(cast_set<size_t>(slot_index));
3362
5
        if (!_segment->can_apply_predicate_safely(cid, *_schema,
3363
5
                                                  _opts.target_cast_type_for_variants, _opts)) {
3364
0
            continue;
3365
0
        }
3366
5
        const auto* tablet_column = _schema->column(cid);
3367
5
        if (tablet_column == nullptr) {
3368
0
            continue;
3369
0
        }
3370
5
        std::shared_ptr<ColumnReader> reader;
3371
5
        Status st =
3372
5
                _segment->get_column_reader(*tablet_column, &reader, _opts.stats, &_opts.io_ctx);
3373
5
        if (st.is<ErrorCode::NOT_FOUND>()) {
3374
4
            continue;
3375
4
        }
3376
1
        RETURN_IF_ERROR(st);
3377
1
        if (reader == nullptr || !reader->has_zone_map()) {
3378
0
            continue;
3379
0
        }
3380
1
        const std::vector<ZoneMapPB>* page_zone_maps = nullptr;
3381
1
        RETURN_IF_ERROR(reader->get_page_zone_maps(iter_opts, &page_zone_maps));
3382
1
        if (page_zone_maps == nullptr || page_zone_maps->empty()) {
3383
0
            continue;
3384
0
        }
3385
1
        auto data_type = _segment->get_data_type_of(*tablet_column, _opts);
3386
1
        if (data_type == nullptr) {
3387
0
            continue;
3388
0
        }
3389
3390
1
        RowRanges column_ranges;
3391
1
        ZoneMapEvalStats page_stats;
3392
9
        for (uint32_t page_index = 0; page_index < page_zone_maps->size(); ++page_index) {
3393
8
            RowRange page_range;
3394
8
            RETURN_IF_ERROR(reader->get_row_range_for_page(page_index, iter_opts, &page_range));
3395
8
            if (!page_range.is_valid() || page_range.to() <= min_rowid) {
3396
0
                continue;
3397
0
            }
3398
8
            ZoneMapEvalContext ctx;
3399
8
            ZoneMapEvalContext::SlotZoneMap slot_zone_map;
3400
8
            slot_zone_map.data_type = data_type;
3401
8
            ZoneMap zone_map;
3402
8
            RETURN_IF_ERROR(
3403
8
                    ZoneMap::from_proto((*page_zone_maps)[page_index], data_type, zone_map));
3404
8
            slot_zone_map.zone_map = std::make_shared<ZoneMap>(std::move(zone_map));
3405
8
            ctx.slots.emplace(slot_index, std::move(slot_zone_map));
3406
8
            const auto result = VExprContext::evaluate_zonemap_filter(slot_conjuncts, ctx);
3407
8
            page_stats.merge_page_eval_stats(ctx.stats);
3408
8
            if (result != ZoneMapFilterResult::kNoMatch) {
3409
4
                column_ranges.add(
3410
4
                        RowRange(std::max<int64_t>(page_range.from(), min_rowid), page_range.to()));
3411
4
            } else {
3412
4
                ++_opts.stats->expr_zonemap_filtered_pages;
3413
4
            }
3414
8
        }
3415
1
        page_stats.accumulate_to(_opts.stats);
3416
1
        RowRanges::ranges_intersection(*row_ranges, column_ranges, row_ranges);
3417
1
        if (row_ranges->is_empty()) {
3418
0
            return Status::OK();
3419
0
        }
3420
1
    }
3421
5
    return Status::OK();
3422
5
}
3423
3424
4.39k
void SegmentIterator::_calculate_common_expr_index_exec_status() {
3425
4.39k
    for (const auto& root_expr_ctx : _common_expr_ctxs_push_down) {
3426
21
        const auto& root_expr = root_expr_ctx->root();
3427
21
        if (root_expr == nullptr) {
3428
0
            continue;
3429
0
        }
3430
21
        _common_expr_to_slotref_map[root_expr_ctx.get()] = std::unordered_map<ColumnId, VExpr*>();
3431
3432
21
        std::stack<VExprSPtr> stack;
3433
21
        stack.emplace(root_expr);
3434
3435
42
        while (!stack.empty()) {
3436
21
            const auto& expr = stack.top();
3437
21
            stack.pop();
3438
3439
30
            for (const auto& child : expr->children()) {
3440
30
                if (child->is_virtual_slot_ref()) {
3441
                    // Expand virtual slot ref to its underlying expression tree and
3442
                    // collect real slot refs used inside. We still associate those
3443
                    // slot refs with the current parent expr node for inverted index
3444
                    // tracking, just like normal slot refs.
3445
0
                    auto* vir_slot_ref = assert_cast<VirtualSlotRef*>(child.get());
3446
0
                    auto vir_expr = vir_slot_ref->get_virtual_column_expr();
3447
0
                    if (vir_expr) {
3448
0
                        std::stack<VExprSPtr> vir_stack;
3449
0
                        vir_stack.emplace(vir_expr);
3450
3451
0
                        while (!vir_stack.empty()) {
3452
0
                            const auto& vir_node = vir_stack.top();
3453
0
                            vir_stack.pop();
3454
3455
0
                            for (const auto& vir_child : vir_node->children()) {
3456
0
                                if (vir_child->is_slot_ref()) {
3457
0
                                    auto* inner_slot_ref = assert_cast<VSlotRef*>(vir_child.get());
3458
0
                                    auto cid = _schema->column_id(inner_slot_ref->column_id());
3459
0
                                    _common_expr_index_exec_status[cid][expr.get()] = false;
3460
0
                                    _common_expr_to_slotref_map[root_expr_ctx.get()]
3461
0
                                                               [inner_slot_ref->column_id()] =
3462
0
                                                                       expr.get();
3463
0
                                }
3464
3465
0
                                if (!vir_child->children().empty()) {
3466
0
                                    vir_stack.emplace(vir_child);
3467
0
                                }
3468
0
                            }
3469
0
                        }
3470
0
                    }
3471
0
                }
3472
                // Example: CAST(v['a'] AS VARCHAR) MATCH 'hello', do not add CAST expr to index tracking.
3473
30
                auto expr_without_cast = VExpr::expr_without_cast(child);
3474
30
                if (expr_without_cast->is_slot_ref() && expr->op() != TExprOpcode::CAST) {
3475
20
                    auto* column_slot_ref = assert_cast<VSlotRef*>(expr_without_cast.get());
3476
20
                    auto cid = _schema->column_id(column_slot_ref->column_id());
3477
20
                    _common_expr_index_exec_status[cid][expr.get()] = false;
3478
20
                    _common_expr_to_slotref_map[root_expr_ctx.get()][column_slot_ref->column_id()] =
3479
20
                            expr.get();
3480
20
                }
3481
30
            }
3482
3483
21
            const auto& children = expr->children();
3484
51
            for (int i = cast_set<int>(children.size()) - 1; i >= 0; --i) {
3485
30
                if (!children[i]->children().empty()) {
3486
0
                    stack.emplace(children[i]);
3487
0
                }
3488
30
            }
3489
21
        }
3490
21
    }
3491
4.39k
}
3492
3493
bool SegmentIterator::_no_need_read_key_data(ColumnId cid, MutableColumnPtr& column,
3494
37.1k
                                             size_t nrows_read) {
3495
37.1k
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_no_need_read_data_opt) {
3496
0
        return false;
3497
0
    }
3498
3499
37.1k
    if (!((_opts.tablet_schema->keys_type() == KeysType::DUP_KEYS ||
3500
37.1k
           (_opts.tablet_schema->keys_type() == KeysType::UNIQUE_KEYS &&
3501
19.8k
            _opts.enable_unique_key_merge_on_write)))) {
3502
16.7k
        return false;
3503
16.7k
    }
3504
3505
20.4k
    if (_opts.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
3506
20.3k
        return false;
3507
20.3k
    }
3508
3509
20
    if (!_opts.tablet_schema->column(cid).is_key()) {
3510
14
        return false;
3511
14
    }
3512
3513
6
    if (_has_delete_predicate(cid)) {
3514
0
        return false;
3515
0
    }
3516
3517
6
    if (!_check_all_conditions_passed_inverted_index_for_column(cid)) {
3518
6
        return false;
3519
6
    }
3520
3521
0
    insert_many_not_null_defaults(column, nrows_read);
3522
0
    return true;
3523
6
}
3524
3525
20.4k
bool SegmentIterator::_has_delete_predicate(ColumnId cid) {
3526
20.4k
    std::set<uint32_t> delete_columns_set;
3527
20.4k
    _opts.delete_condition_predicates->get_all_column_ids(delete_columns_set);
3528
20.4k
    return delete_columns_set.contains(cid);
3529
20.4k
}
3530
3531
18.0k
bool SegmentIterator::_can_opt_limit_reads() {
3532
18.0k
    if (_opts.read_limit == 0) {
3533
18.0k
        return false;
3534
18.0k
    }
3535
3536
    // If SegmentIterator still needs to evaluate predicates/common exprs, LIMIT must be applied to
3537
    // post-filter rows by _apply_read_limit_to_selected_rows(); capping the raw read here could
3538
    // return fewer rows than the query LIMIT.
3539
7
    if (_is_need_vec_eval || _is_need_short_eval || _is_need_expr_eval) {
3540
3
        return false;
3541
3
    }
3542
3543
4
    if (_opts.delete_condition_predicates->num_of_column_predicate() > 0) {
3544
1
        return false;
3545
1
    }
3546
3547
3
    bool all_true = std::ranges::all_of(_schema->column_ids(), [this](auto cid) {
3548
3
        if (cid == _opts.tablet_schema->delete_sign_idx()) {
3549
0
            return true;
3550
0
        }
3551
3
        if (_check_all_conditions_passed_inverted_index_for_column(cid, true)) {
3552
2
            return true;
3553
2
        }
3554
1
        return false;
3555
3
    });
3556
3557
3
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_1", {
3558
3
        LOG(INFO) << "col_predicates: " << _col_predicates.size() << ", all_true: " << all_true;
3559
3
    })
3560
3561
3
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_2", {
3562
3
        if (all_true) {
3563
3
            return Status::Error<ErrorCode::INTERNAL_ERROR>("topn opt 2 execute failed");
3564
3
        }
3565
3
    })
3566
3567
3
    return all_true;
3568
3
}
3569
3570
// Before get next batch. make sure all virtual columns in block has type ColumnNothing.
3571
18.0k
void SegmentIterator::_init_virtual_columns(Block* block) {
3572
18.0k
    for (const auto& [cid, expr_ctx] : _virtual_column_exprs) {
3573
0
        auto idx = _schema->column_index(cid);
3574
0
        auto& col_with_type_and_name = block->get_by_position(idx);
3575
0
        col_with_type_and_name.column = ColumnNothing::create(0);
3576
0
        col_with_type_and_name.type = expr_ctx->root()->data_type();
3577
0
    }
3578
18.0k
}
3579
3580
14.5k
Status SegmentIterator::_materialization_of_virtual_column(Block* block) {
3581
    // Some expr can not process empty block, such as function `element_at`.
3582
    // So materialize virtual column in advance to avoid errors.
3583
14.5k
    if (_selected_size == 0) {
3584
38
        for (const auto& [cid, expr_ctx] : _virtual_column_exprs) {
3585
0
            auto idx = _schema->column_index(cid);
3586
0
            auto& col_with_type_and_name = block->get_by_position(idx);
3587
0
            col_with_type_and_name.column = expr_ctx->root()->data_type()->create_column();
3588
0
            col_with_type_and_name.type = expr_ctx->root()->data_type();
3589
0
        }
3590
38
        return Status::OK();
3591
38
    }
3592
14.5k
    if (_virtual_column_exprs.empty()) {
3593
14.5k
        return Status::OK();
3594
14.5k
    }
3595
3596
0
    for (const auto& cid_and_expr : _virtual_column_exprs) {
3597
0
        auto cid = cid_and_expr.first;
3598
0
        auto column_expr = cid_and_expr.second;
3599
0
        auto materialized_pos = _schema->column_index(cid);
3600
0
        auto& column = block->get_by_position(materialized_pos).column;
3601
0
        if (check_and_get_column<const ColumnNothing>(column.get())) {
3602
0
            VLOG_DEBUG << fmt::format("Virtual column is doing materialization, cid {}, col idx {}",
3603
0
                                      cid, materialized_pos);
3604
0
            ColumnPtr result_column;
3605
            // The first block column may still be ColumnNothing(0) for a virtual column, while
3606
            // predicates have already reduced _selected_size. Evaluate the expression over the
3607
            // selected row count instead of Block::rows().
3608
0
            RETURN_IF_ERROR(column_expr->root()->execute_column(column_expr.get(), block, nullptr,
3609
0
                                                                _selected_size, result_column));
3610
3611
0
            block->replace_by_position(materialized_pos, std::move(result_column));
3612
0
        }
3613
0
    }
3614
0
    return Status::OK();
3615
0
}
3616
3617
4.39k
void SegmentIterator::_prepare_score_column_materialization() {
3618
4.39k
    if (_score_runtime == nullptr) {
3619
4.39k
        return;
3620
4.39k
    }
3621
3622
0
    ScoreRangeFilterPtr filter;
3623
0
    if (_score_runtime->has_score_range_filter()) {
3624
0
        const auto& range_info = _score_runtime->get_score_range_info();
3625
0
        filter = std::make_shared<ScoreRangeFilter>(range_info->op, range_info->threshold);
3626
0
    }
3627
3628
0
    IColumn::MutablePtr result_column;
3629
0
    auto result_row_ids = std::make_unique<std::vector<uint64_t>>();
3630
0
    if (_score_runtime->get_limit() > 0 && _col_predicates.empty() &&
3631
0
        _common_expr_ctxs_push_down.empty()) {
3632
0
        OrderType order_type = _score_runtime->is_asc() ? OrderType::ASC : OrderType::DESC;
3633
0
        _index_query_context->collection_similarity->get_topn_bm25_scores(
3634
0
                &_row_bitmap, result_column, result_row_ids, order_type,
3635
0
                _score_runtime->get_limit(), filter);
3636
0
    } else {
3637
0
        _index_query_context->collection_similarity->get_bm25_scores(&_row_bitmap, result_column,
3638
0
                                                                     result_row_ids, filter);
3639
0
    }
3640
0
    const size_t dst_col_idx = _score_runtime->get_dest_column_idx();
3641
0
    auto* column_iter = _column_iterators[_schema->column_id(dst_col_idx)].get();
3642
0
    auto* virtual_column_iter = dynamic_cast<VirtualColumnIterator*>(column_iter);
3643
0
    virtual_column_iter->prepare_materialization(
3644
0
            std::move(result_column),
3645
0
            std::shared_ptr<std::vector<uint64_t>>(std::move(result_row_ids)));
3646
0
}
3647
3648
} // namespace segment_v2
3649
} // namespace doris