Coverage Report

Created: 2026-05-22 17:47

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