Coverage Report

Created: 2026-05-28 18:51

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