Coverage Report

Created: 2026-06-10 02:13

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