Coverage Report

Created: 2026-03-20 13:28

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