Coverage Report

Created: 2026-05-12 22:35

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