Coverage Report

Created: 2026-08-03 12:13

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