Coverage Report

Created: 2026-05-29 15:19

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
        bool ann_range_search_executed = false;
1370
0
        RETURN_IF_ERROR(expr_ctx->evaluate_ann_range_search(
1371
0
                _index_iterators, _schema->column_ids(), _column_iterators,
1372
0
                _common_expr_to_slotref_map, _row_bitmap, ann_index_stats,
1373
0
                enable_ann_index_result_cache, &ann_range_search_executed));
1374
0
        if (ann_range_search_executed) {
1375
0
            _opts.stats->ann_index_range_search_cnt++;
1376
0
        }
1377
0
        _opts.stats->rows_ann_index_range_filtered += (origin_rows - _row_bitmap.cardinality());
1378
0
        _opts.stats->ann_index_load_ns += ann_index_stats.load_index_costs_ns.value();
1379
0
        _opts.stats->ann_index_range_search_ns += ann_index_stats.search_costs_ns.value();
1380
0
        _opts.stats->ann_ivf_on_disk_load_ns += ann_index_stats.ivf_on_disk_load_costs_ns.value();
1381
0
        _opts.stats->ann_ivf_on_disk_cache_hit_cnt +=
1382
0
                ann_index_stats.ivf_on_disk_cache_hit_cnt.value();
1383
0
        _opts.stats->ann_ivf_on_disk_cache_miss_cnt +=
1384
0
                ann_index_stats.ivf_on_disk_cache_miss_cnt.value();
1385
0
        _opts.stats->ann_range_engine_search_ns += ann_index_stats.engine_search_ns.value();
1386
0
        _opts.stats->ann_range_result_convert_ns += ann_index_stats.result_process_costs_ns.value();
1387
0
        _opts.stats->ann_range_engine_convert_ns += ann_index_stats.engine_convert_ns.value();
1388
0
        _opts.stats->ann_range_pre_process_ns += ann_index_stats.engine_prepare_ns.value();
1389
0
        _opts.stats->ann_fall_back_brute_force_cnt += ann_index_stats.fall_back_brute_force_cnt;
1390
0
        _opts.stats->ann_index_range_cache_hits += ann_index_stats.range_cache_hits.value();
1391
0
    }
1392
1393
0
    return Status::OK();
1394
0
}
1395
1396
0
bool SegmentIterator::_downgrade_without_index(Status res, bool need_remaining) {
1397
0
    bool is_fallback =
1398
0
            _opts.runtime_state->query_options().enable_fallback_on_missing_inverted_index;
1399
0
    if ((res.code() == ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND && is_fallback) ||
1400
0
        res.code() == ErrorCode::INVERTED_INDEX_BYPASS ||
1401
0
        res.code() == ErrorCode::INVERTED_INDEX_EVALUATE_SKIPPED ||
1402
0
        (res.code() == ErrorCode::INVERTED_INDEX_NO_TERMS && need_remaining) ||
1403
0
        res.code() == ErrorCode::INVERTED_INDEX_FILE_CORRUPTED) {
1404
        // 1. INVERTED_INDEX_FILE_NOT_FOUND means index file has not been built,
1405
        //    usually occurs when creating a new index, queries can be downgraded
1406
        //    without index.
1407
        // 2. INVERTED_INDEX_BYPASS means the hit of condition by index
1408
        //    has reached the optimal limit, downgrade without index query can
1409
        //    improve query performance.
1410
        // 3. INVERTED_INDEX_EVALUATE_SKIPPED means the inverted index is not
1411
        //    suitable for executing this predicate, skipped it and filter data
1412
        //    by function later.
1413
        // 4. INVERTED_INDEX_NO_TERMS means the column has fulltext index,
1414
        //    but the column condition value no terms in specified parser,
1415
        //    such as: where A = '' and B = ','
1416
        //    the predicate of A and B need downgrade without index query.
1417
        // 5. INVERTED_INDEX_FILE_CORRUPTED means the index file is corrupted,
1418
        //    such as when index segment files are not generated
1419
        // above case can downgrade without index query
1420
0
        _opts.stats->inverted_index_downgrade_count++;
1421
0
        if (!res.is<ErrorCode::INVERTED_INDEX_BYPASS>()) {
1422
0
            LOG(INFO) << "will downgrade without index to evaluate predicate, because of res: "
1423
0
                      << res;
1424
0
        } else {
1425
0
            VLOG_DEBUG << "will downgrade without index to evaluate predicate, because of res: "
1426
0
                       << res;
1427
0
        }
1428
0
        return true;
1429
0
    }
1430
0
    return false;
1431
0
}
1432
1433
0
bool SegmentIterator::_column_has_fulltext_index(int32_t cid) {
1434
0
    bool has_fulltext_index =
1435
0
            _index_iterators[cid] != nullptr &&
1436
0
            _index_iterators[cid]->get_reader(InvertedIndexReaderType::FULLTEXT) &&
1437
0
            _index_iterators[cid]->get_reader(InvertedIndexReaderType::STRING_TYPE) == nullptr;
1438
1439
0
    return has_fulltext_index;
1440
0
}
1441
1442
0
inline bool SegmentIterator::_inverted_index_not_support_pred_type(const PredicateType& type) {
1443
0
    return type == PredicateType::BF || type == PredicateType::BITMAP_FILTER;
1444
0
}
1445
1446
Status SegmentIterator::_apply_inverted_index_on_column_predicate(
1447
        std::shared_ptr<ColumnPredicate> pred,
1448
0
        std::vector<std::shared_ptr<ColumnPredicate>>& remaining_predicates, bool* continue_apply) {
1449
0
    if (!_check_apply_by_inverted_index(pred)) {
1450
0
        remaining_predicates.emplace_back(pred);
1451
0
    } else {
1452
0
        bool need_remaining_after_evaluate = _column_has_fulltext_index(pred->column_id()) &&
1453
0
                                             PredicateTypeTraits::is_equal_or_list(pred->type());
1454
0
        Status res =
1455
0
                pred->evaluate(_storage_name_and_type[pred->column_id()],
1456
0
                               _index_iterators[pred->column_id()].get(), num_rows(), &_row_bitmap);
1457
0
        if (!res.ok()) {
1458
0
            if (_downgrade_without_index(res, need_remaining_after_evaluate)) {
1459
0
                remaining_predicates.emplace_back(pred);
1460
0
                return Status::OK();
1461
0
            }
1462
0
            LOG(WARNING) << "failed to evaluate index"
1463
0
                         << ", column predicate type: " << pred->pred_type_string(pred->type())
1464
0
                         << ", error msg: " << res;
1465
0
            return res;
1466
0
        }
1467
1468
0
        if (_row_bitmap.isEmpty()) {
1469
            // all rows have been pruned, no need to process further predicates
1470
0
            *continue_apply = false;
1471
0
        }
1472
1473
0
        if (need_remaining_after_evaluate) {
1474
0
            remaining_predicates.emplace_back(pred);
1475
0
            return Status::OK();
1476
0
        }
1477
0
        if (!pred->is_runtime_filter()) {
1478
0
            _column_predicate_index_exec_status[pred->column_id()][pred] = true;
1479
0
        }
1480
0
    }
1481
0
    return Status::OK();
1482
0
}
1483
1484
27.1k
bool SegmentIterator::_need_read_data(ColumnId cid) {
1485
27.1k
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_no_need_read_data_opt) {
1486
0
        return true;
1487
0
    }
1488
    // only support DUP_KEYS and UNIQUE_KEYS with MOW
1489
27.1k
    if (!((_opts.tablet_schema->keys_type() == KeysType::DUP_KEYS ||
1490
27.1k
           (_opts.tablet_schema->keys_type() == KeysType::UNIQUE_KEYS &&
1491
11.1k
            _opts.enable_unique_key_merge_on_write)))) {
1492
7.58k
        return true;
1493
7.58k
    }
1494
    // this is a virtual column, we always need to read data
1495
19.5k
    if (this->_vir_cid_to_idx_in_block.contains(cid)) {
1496
0
        return true;
1497
0
    }
1498
1499
    // if there is a delete predicate, we always need to read data
1500
19.5k
    if (_has_delete_predicate(cid)) {
1501
1.74k
        return true;
1502
1.74k
    }
1503
17.8k
    if (_output_columns.count(-1)) {
1504
        // if _output_columns contains -1, it means that the light
1505
        // weight schema change may not be enabled or other reasons
1506
        // caused the column unique_id not be set, to prevent errors
1507
        // occurring, return true here that column data needs to be read
1508
0
        return true;
1509
0
    }
1510
    // Check the following conditions:
1511
    // 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]')
1512
    //    and it's not marked for projection in '_output_columns'.
1513
    // 2. Or, if the column is an inverted index column and it's marked for projection in '_output_columns',
1514
    //    and the operation is a push down of the 'COUNT_ON_INDEX' aggregation function.
1515
    // 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.
1516
    // Then, return false.
1517
17.8k
    const auto& column = _opts.tablet_schema->column(cid);
1518
    // Different subcolumns may share the same parent_unique_id, so we choose to abandon this optimization.
1519
17.8k
    if (column.is_extracted_column() &&
1520
17.8k
        _opts.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
1521
13
        return true;
1522
13
    }
1523
17.8k
    int32_t unique_id = column.unique_id();
1524
17.8k
    if (unique_id < 0) {
1525
1
        unique_id = column.parent_unique_id();
1526
1
    }
1527
17.8k
    if ((_need_read_data_indices.contains(cid) && !_need_read_data_indices[cid] &&
1528
17.8k
         !_output_columns.contains(unique_id)) ||
1529
17.8k
        (_need_read_data_indices.contains(cid) && !_need_read_data_indices[cid] &&
1530
17.8k
         _output_columns.count(unique_id) == 1 &&
1531
17.8k
         _opts.push_down_agg_type_opt == TPushAggOp::COUNT_ON_INDEX)) {
1532
1
        VLOG_DEBUG << "SegmentIterator no need read data for column: "
1533
0
                   << _opts.tablet_schema->column_by_uid(unique_id).name();
1534
1
        return false;
1535
1
    }
1536
17.8k
    return true;
1537
17.8k
}
1538
1539
0
Status SegmentIterator::_apply_inverted_index() {
1540
0
    std::vector<std::shared_ptr<ColumnPredicate>> remaining_predicates;
1541
0
    std::set<std::shared_ptr<ColumnPredicate>> no_need_to_pass_column_predicate_set;
1542
1543
0
    for (auto pred : _col_predicates) {
1544
0
        if (no_need_to_pass_column_predicate_set.count(pred) > 0) {
1545
0
            continue;
1546
0
        } else {
1547
0
            bool continue_apply = true;
1548
0
            RETURN_IF_ERROR(_apply_inverted_index_on_column_predicate(pred, remaining_predicates,
1549
0
                                                                      &continue_apply));
1550
0
            if (!continue_apply) {
1551
0
                break;
1552
0
            }
1553
0
        }
1554
0
    }
1555
1556
0
    _col_predicates = std::move(remaining_predicates);
1557
0
    return Status::OK();
1558
0
}
1559
1560
/**
1561
 * @brief Checks if all conditions related to a specific column have passed in both
1562
 * `_column_predicate_inverted_index_status` and `_common_expr_inverted_index_status`.
1563
 *
1564
 * This function first checks the conditions in `_column_predicate_inverted_index_status`
1565
 * for the given `ColumnId`. If all conditions pass, it sets `default_return` to `true`.
1566
 * It then checks the conditions in `_common_expr_inverted_index_status` for the same column.
1567
 *
1568
 * The function returns `true` if all conditions in both maps pass. If any condition fails
1569
 * in either map, the function immediately returns `false`. If the column does not exist
1570
 * in one of the maps, the function returns `default_return`.
1571
 *
1572
 * @param cid The ColumnId of the column to check.
1573
 * @param default_return The default value to return if the column is not found in the status maps.
1574
 * @return true if all conditions in both status maps pass, or if the column is not found
1575
 *         and `default_return` is true.
1576
 * @return false if any condition in either status map fails, or if the column is not found
1577
 *         and `default_return` is false.
1578
 */
1579
bool SegmentIterator::_check_all_conditions_passed_inverted_index_for_column(ColumnId cid,
1580
3
                                                                             bool default_return) {
1581
3
    auto pred_it = _column_predicate_index_exec_status.find(cid);
1582
3
    if (pred_it != _column_predicate_index_exec_status.end()) {
1583
2
        const auto& pred_map = pred_it->second;
1584
2
        bool pred_passed = std::all_of(pred_map.begin(), pred_map.end(),
1585
2
                                       [](const auto& pred_entry) { return pred_entry.second; });
1586
2
        if (!pred_passed) {
1587
1
            return false;
1588
1
        } else {
1589
1
            default_return = true;
1590
1
        }
1591
2
    }
1592
1593
2
    auto expr_it = _common_expr_index_exec_status.find(cid);
1594
2
    if (expr_it != _common_expr_index_exec_status.end()) {
1595
0
        const auto& expr_map = expr_it->second;
1596
0
        return std::all_of(expr_map.begin(), expr_map.end(),
1597
0
                           [](const auto& expr_entry) { return expr_entry.second; });
1598
0
    }
1599
2
    return default_return;
1600
2
}
1601
1602
2.82k
Status SegmentIterator::_init_return_column_iterators() {
1603
2.82k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_return_column_iterators_timer_ns);
1604
2.82k
    if (_cur_rowid >= num_rows()) {
1605
0
        return Status::OK();
1606
0
    }
1607
1608
7.05k
    for (auto cid : _schema->column_ids()) {
1609
7.05k
        if (_schema->column(cid)->name() == BeConsts::ROWID_COL) {
1610
0
            _column_iterators[cid].reset(
1611
0
                    new RowIdColumnIterator(_opts.tablet_id, _opts.rowset_id, _segment->id()));
1612
0
            continue;
1613
0
        }
1614
1615
7.05k
        if (_schema->column(cid)->name().starts_with(BeConsts::GLOBAL_ROWID_COL)) {
1616
0
            auto& id_file_map = _opts.runtime_state->get_id_file_map();
1617
0
            uint32_t file_id = id_file_map->get_file_mapping_id(std::make_shared<FileMapping>(
1618
0
                    _opts.tablet_id, _opts.rowset_id, _segment->id()));
1619
0
            _column_iterators[cid].reset(new RowIdColumnIteratorV2(
1620
0
                    IdManager::ID_VERSION, BackendOptions::get_backend_id(), file_id));
1621
0
            continue;
1622
0
        }
1623
1624
7.05k
        if (_schema->column(cid)->name().starts_with(BeConsts::VIRTUAL_COLUMN_PREFIX)) {
1625
0
            _column_iterators[cid] = std::make_unique<VirtualColumnIterator>();
1626
0
            continue;
1627
0
        }
1628
1629
7.05k
        std::set<ColumnId> del_cond_id_set;
1630
7.05k
        _opts.delete_condition_predicates->get_all_column_ids(del_cond_id_set);
1631
7.05k
        std::vector<bool> tmp_is_pred_column;
1632
7.05k
        tmp_is_pred_column.resize(_schema->columns().size(), false);
1633
7.05k
        for (auto predicate : _col_predicates) {
1634
0
            auto p_cid = predicate->column_id();
1635
0
            tmp_is_pred_column[p_cid] = true;
1636
0
        }
1637
        // handle delete_condition
1638
7.05k
        for (auto d_cid : del_cond_id_set) {
1639
1.32k
            tmp_is_pred_column[d_cid] = true;
1640
1.32k
        }
1641
1642
7.05k
        if (_column_iterators[cid] == nullptr) {
1643
7.05k
            RETURN_IF_ERROR(_segment->new_column_iterator(_opts.tablet_schema->column(cid),
1644
7.05k
                                                          &_column_iterators[cid], &_opts,
1645
7.05k
                                                          &_variant_sparse_column_cache));
1646
7.05k
            ColumnIteratorOptions iter_opts {
1647
7.05k
                    .use_page_cache = _opts.use_page_cache,
1648
                    // If the col is predicate column, then should read the last page to check
1649
                    // if the column is full dict encoding
1650
7.05k
                    .is_predicate_column = tmp_is_pred_column[cid],
1651
7.05k
                    .file_reader = _file_reader.get(),
1652
7.05k
                    .stats = _opts.stats,
1653
7.05k
                    .io_ctx = _opts.io_ctx,
1654
7.05k
            };
1655
7.05k
            RETURN_IF_ERROR(_column_iterators[cid]->init(iter_opts));
1656
7.05k
        }
1657
7.05k
    }
1658
1659
2.82k
#ifndef NDEBUG
1660
2.82k
    for (auto pair : _vir_cid_to_idx_in_block) {
1661
0
        ColumnId vir_col_cid = pair.first;
1662
0
        DCHECK(_column_iterators[vir_col_cid] != nullptr)
1663
0
                << "Virtual column iterator for " << vir_col_cid << " should not be null";
1664
0
        ColumnIterator* column_iter = _column_iterators[vir_col_cid].get();
1665
0
        DCHECK(dynamic_cast<VirtualColumnIterator*>(column_iter) != nullptr)
1666
0
                << "Virtual column iterator for " << vir_col_cid
1667
0
                << " should be VirtualColumnIterator";
1668
0
    }
1669
2.82k
#endif
1670
2.82k
    return Status::OK();
1671
2.82k
}
1672
1673
2.82k
Status SegmentIterator::_init_index_iterators() {
1674
2.82k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_index_iterators_timer_ns);
1675
2.82k
    if (_cur_rowid >= num_rows()) {
1676
0
        return Status::OK();
1677
0
    }
1678
1679
2.82k
    _index_query_context = std::make_shared<IndexQueryContext>();
1680
2.82k
    _index_query_context->io_ctx = &_opts.io_ctx;
1681
2.82k
    _index_query_context->stats = _opts.stats;
1682
2.82k
    _index_query_context->runtime_state = _opts.runtime_state;
1683
1684
2.82k
    if (_score_runtime) {
1685
0
        _index_query_context->collection_statistics = _opts.collection_statistics;
1686
0
        _index_query_context->collection_similarity = std::make_shared<CollectionSimilarity>();
1687
0
        _index_query_context->query_limit = _score_runtime->get_limit();
1688
0
        _index_query_context->is_asc = _score_runtime->is_asc();
1689
0
    }
1690
1691
    // Inverted index iterators
1692
7.05k
    for (auto cid : _schema->column_ids()) {
1693
        // Use segment’s own index_meta, for compatibility with future indexing needs to default to lowercase.
1694
7.05k
        if (_index_iterators[cid] == nullptr) {
1695
            // In the _opts.tablet_schema, the sub-column type information for the variant is FieldType::OLAP_FIELD_TYPE_VARIANT.
1696
            // This is because the sub-column is created in create_materialized_variant_column.
1697
            // We use this column to locate the metadata for the inverted index, which requires a unique_id and path.
1698
7.05k
            const auto& column = _opts.tablet_schema->column(cid);
1699
7.05k
            std::vector<const TabletIndex*> inverted_indexs;
1700
            // Keep shared_ptr alive to prevent use-after-free when accessing raw pointers
1701
7.05k
            TabletIndexes inverted_indexs_holder;
1702
            // If the column is an extracted column, we need to find the sub-column in the parent column reader.
1703
7.05k
            std::shared_ptr<ColumnReader> column_reader;
1704
7.05k
            if (column.is_extracted_column()) {
1705
6
                if (!_segment->_column_reader_cache->get_column_reader(
1706
6
                            column.parent_unique_id(), &column_reader, _opts.stats) ||
1707
6
                    column_reader == nullptr) {
1708
0
                    continue;
1709
0
                }
1710
6
                auto* variant_reader = assert_cast<VariantColumnReader*>(column_reader.get());
1711
6
                DataTypePtr data_type = _storage_name_and_type[cid].second;
1712
6
                if (data_type != nullptr &&
1713
6
                    data_type->get_primitive_type() == PrimitiveType::TYPE_VARIANT) {
1714
0
                    DataTypePtr inferred_type;
1715
0
                    Status st = variant_reader->infer_data_type_for_path(
1716
0
                            &inferred_type, column, _opts, _segment->_column_reader_cache.get());
1717
0
                    if (st.ok() && inferred_type != nullptr) {
1718
0
                        data_type = inferred_type;
1719
0
                    }
1720
0
                }
1721
6
                inverted_indexs_holder = variant_reader->find_subcolumn_tablet_indexes(
1722
6
                        column, data_type, _opts.stats);
1723
                // Extract raw pointers from shared_ptr for iteration
1724
6
                for (const auto& index_ptr : inverted_indexs_holder) {
1725
0
                    inverted_indexs.push_back(index_ptr.get());
1726
0
                }
1727
6
            }
1728
            // If the column is not an extracted column, we can directly get the inverted index metadata from the tablet schema.
1729
7.05k
            else {
1730
7.05k
                inverted_indexs = _segment->_tablet_schema->inverted_indexs(column);
1731
7.05k
            }
1732
7.05k
            if (column.is_extracted_column() && inverted_indexs.empty() && _opts.stats != nullptr) {
1733
6
                const auto relative_path = column.path_info_ptr()->copy_pop_front().get_path();
1734
6
                const auto diagnostic = fmt::format(
1735
6
                        "[VariantSearchBinding] phase=init_index_iterators "
1736
6
                        "result=no_candidate tablet_id={} rowset_id={} segment_id={} cid={} "
1737
6
                        "logical_path={} relative_path={} materialized_column={}",
1738
6
                        _tablet_id, _segment->rowset_id().to_string(), _segment->id(), cid,
1739
6
                        column.path_info_ptr()->get_path(), relative_path, column.name());
1740
6
                VLOG_DEBUG << diagnostic;
1741
6
                _opts.stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
1742
6
            }
1743
7.05k
            for (const auto& inverted_index : inverted_indexs) {
1744
2.56k
                const bool had_iterator = _index_iterators[cid] != nullptr;
1745
2.56k
                RETURN_IF_ERROR(_segment->new_index_iterator(column, inverted_index, _opts,
1746
2.56k
                                                             &_index_iterators[cid]));
1747
2.56k
                if ((column.is_extracted_column() || column.is_variant_type()) &&
1748
2.56k
                    _opts.stats != nullptr) {
1749
0
                    const auto diagnostic = fmt::format(
1750
0
                            "[VariantSearchBinding] phase=init_index_iterators "
1751
0
                            "result={} tablet_id={} rowset_id={} segment_id={} cid={} "
1752
0
                            "logical_path={} materialized_column={} index_id={} suffix={} "
1753
0
                            "field_pattern={} iterator_state={}",
1754
0
                            _index_iterators[cid] == nullptr ? "no_iterator" : "accepted",
1755
0
                            _tablet_id, _segment->rowset_id().to_string(), _segment->id(), cid,
1756
0
                            column.has_path_info() ? column.path_info_ptr()->get_path()
1757
0
                                                   : column.name(),
1758
0
                            column.name(), inverted_index->index_id(),
1759
0
                            inverted_index->get_index_suffix(), inverted_index->field_pattern(),
1760
0
                            had_iterator ? "preserved" : "created");
1761
0
                    VLOG_DEBUG << diagnostic;
1762
0
                    _opts.stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
1763
0
                }
1764
2.56k
            }
1765
7.05k
            if (_index_iterators[cid] != nullptr) {
1766
2.55k
                _index_iterators[cid]->set_context(_index_query_context);
1767
2.55k
            }
1768
7.05k
        }
1769
7.05k
    }
1770
1771
    // Ann index iterators
1772
7.05k
    for (auto cid : _schema->column_ids()) {
1773
7.05k
        if (_index_iterators[cid] == nullptr) {
1774
4.50k
            const auto& column = _opts.tablet_schema->column(cid);
1775
4.50k
            const auto* index_meta = _segment->_tablet_schema->ann_index(column);
1776
4.50k
            if (index_meta) {
1777
1
                RETURN_IF_ERROR(_segment->new_index_iterator(column, index_meta, _opts,
1778
1
                                                             &_index_iterators[cid]));
1779
1780
1
                if (_index_iterators[cid] != nullptr) {
1781
1
                    _index_iterators[cid]->set_context(_index_query_context);
1782
1
                }
1783
1
            }
1784
4.50k
        }
1785
7.05k
    }
1786
1787
2.82k
    return Status::OK();
1788
2.82k
}
1789
1790
Status SegmentIterator::_lookup_ordinal(const RowCursor& key, bool is_include, rowid_t upper_bound,
1791
0
                                        rowid_t* rowid) {
1792
0
    if (_segment->_tablet_schema->keys_type() == UNIQUE_KEYS &&
1793
0
        _segment->get_primary_key_index() != nullptr) {
1794
0
        return _lookup_ordinal_from_pk_index(key, is_include, rowid);
1795
0
    }
1796
0
    return _lookup_ordinal_from_sk_index(key, is_include, upper_bound, rowid);
1797
0
}
1798
1799
// look up one key to get its ordinal at which can get data by using short key index.
1800
// 'upper_bound' is defined the max ordinal the function will search.
1801
// We use upper_bound to reduce search times.
1802
// If we find a valid ordinal, it will be set in rowid and with Status::OK()
1803
// If we can not find a valid key in this segment, we will set rowid to upper_bound
1804
// Otherwise return error.
1805
// 1. get [start, end) ordinal through short key index
1806
// 2. binary search to find exact ordinal that match the input condition
1807
// Make is_include template to reduce branch
1808
Status SegmentIterator::_lookup_ordinal_from_sk_index(const RowCursor& key, bool is_include,
1809
0
                                                      rowid_t upper_bound, rowid_t* rowid) {
1810
0
    const ShortKeyIndexDecoder* sk_index_decoder = _segment->get_short_key_index();
1811
0
    DCHECK(sk_index_decoder != nullptr);
1812
1813
0
    std::string index_key;
1814
0
    key.encode_key_with_padding(&index_key, _segment->_tablet_schema->num_short_key_columns(),
1815
0
                                is_include);
1816
1817
0
    const auto& key_col_ids = key.schema()->column_ids();
1818
1819
    // Clone the key once and pad CHAR fields to storage format before the binary search.
1820
    // _seek_block holds storage-format data where CHAR is zero-padded to column length,
1821
    // while RowCursor holds CHAR in compute format (unpadded). Padding once here avoids
1822
    // repeated allocation inside the comparison loop.
1823
0
    RowCursor padded_key = key.clone();
1824
0
    padded_key.pad_char_fields();
1825
1826
0
    ssize_t start_block_id = 0;
1827
0
    auto start_iter = sk_index_decoder->lower_bound(index_key);
1828
0
    if (start_iter.valid()) {
1829
        // Because previous block may contain this key, so we should set rowid to
1830
        // last block's first row.
1831
0
        start_block_id = start_iter.ordinal();
1832
0
        if (start_block_id > 0) {
1833
0
            start_block_id--;
1834
0
        }
1835
0
    } else {
1836
        // When we don't find a valid index item, which means all short key is
1837
        // smaller than input key, this means that this key may exist in the last
1838
        // row block. so we set the rowid to first row of last row block.
1839
0
        start_block_id = sk_index_decoder->num_items() - 1;
1840
0
    }
1841
0
    rowid_t start = cast_set<rowid_t>(start_block_id) * sk_index_decoder->num_rows_per_block();
1842
1843
0
    rowid_t end = upper_bound;
1844
0
    auto end_iter = sk_index_decoder->upper_bound(index_key);
1845
0
    if (end_iter.valid()) {
1846
0
        end = cast_set<rowid_t>(end_iter.ordinal()) * sk_index_decoder->num_rows_per_block();
1847
0
    }
1848
1849
    // binary search to find the exact key
1850
0
    while (start < end) {
1851
0
        rowid_t mid = (start + end) / 2;
1852
0
        RETURN_IF_ERROR(_seek_and_peek(mid));
1853
0
        int cmp = _compare_short_key_with_seek_block(padded_key, key_col_ids);
1854
0
        if (cmp > 0) {
1855
0
            start = mid + 1;
1856
0
        } else if (cmp == 0) {
1857
0
            if (is_include) {
1858
                // lower bound
1859
0
                end = mid;
1860
0
            } else {
1861
                // upper bound
1862
0
                start = mid + 1;
1863
0
            }
1864
0
        } else {
1865
0
            end = mid;
1866
0
        }
1867
0
    }
1868
1869
0
    *rowid = start;
1870
0
    return Status::OK();
1871
0
}
1872
1873
Status SegmentIterator::_lookup_ordinal_from_pk_index(const RowCursor& key, bool is_include,
1874
0
                                                      rowid_t* rowid) {
1875
0
    DCHECK(_segment->_tablet_schema->keys_type() == UNIQUE_KEYS);
1876
0
    const PrimaryKeyIndexReader* pk_index_reader = _segment->get_primary_key_index();
1877
0
    DCHECK(pk_index_reader != nullptr);
1878
1879
0
    std::string index_key;
1880
0
    key.encode_key_with_padding<true>(&index_key, _segment->_tablet_schema->num_key_columns(),
1881
0
                                      is_include);
1882
0
    if (index_key < _segment->min_key()) {
1883
0
        *rowid = 0;
1884
0
        return Status::OK();
1885
0
    } else if (index_key > _segment->max_key()) {
1886
0
        *rowid = num_rows();
1887
0
        return Status::OK();
1888
0
    }
1889
0
    bool exact_match = false;
1890
1891
0
    std::unique_ptr<segment_v2::IndexedColumnIterator> index_iterator;
1892
0
    RETURN_IF_ERROR(pk_index_reader->new_iterator(&index_iterator, _opts.stats));
1893
1894
0
    Status status = index_iterator->seek_at_or_after(&index_key, &exact_match);
1895
0
    if (UNLIKELY(!status.ok())) {
1896
0
        *rowid = num_rows();
1897
0
        if (status.is<ENTRY_NOT_FOUND>()) {
1898
0
            return Status::OK();
1899
0
        }
1900
0
        return status;
1901
0
    }
1902
0
    *rowid = cast_set<rowid_t>(index_iterator->get_current_ordinal());
1903
1904
    // The sequence column needs to be removed from primary key index when comparing key
1905
0
    bool has_seq_col = _segment->_tablet_schema->has_sequence_col();
1906
    // Used to get key range from primary key index,
1907
    // for mow with cluster key table, we should get key range from short key index.
1908
0
    DCHECK(_segment->_tablet_schema->cluster_key_uids().empty());
1909
1910
    // if full key is exact_match, the primary key without sequence column should also the same
1911
0
    if (has_seq_col && !exact_match) {
1912
0
        size_t seq_col_length =
1913
0
                _segment->_tablet_schema->column(_segment->_tablet_schema->sequence_col_idx())
1914
0
                        .length() +
1915
0
                1;
1916
0
        auto index_type = DataTypeFactory::instance().create_data_type(
1917
0
                _segment->_pk_index_reader->type(), 1, 0);
1918
0
        auto index_column = index_type->create_column();
1919
0
        size_t num_to_read = 1;
1920
0
        size_t num_read = num_to_read;
1921
0
        RETURN_IF_ERROR(index_iterator->next_batch(&num_read, index_column));
1922
0
        DCHECK(num_to_read == num_read);
1923
1924
0
        Slice sought_key =
1925
0
                Slice(index_column->get_data_at(0).data, index_column->get_data_at(0).size);
1926
0
        Slice sought_key_without_seq =
1927
0
                Slice(sought_key.get_data(), sought_key.get_size() - seq_col_length);
1928
1929
        // compare key
1930
0
        if (Slice(index_key).compare(sought_key_without_seq) == 0) {
1931
0
            exact_match = true;
1932
0
        }
1933
0
    }
1934
1935
    // find the key in primary key index, and the is_include is false, so move
1936
    // to the next row.
1937
0
    if (exact_match && !is_include) {
1938
0
        *rowid += 1;
1939
0
    }
1940
0
    return Status::OK();
1941
0
}
1942
1943
// seek to the row and load that row to _key_cursor
1944
0
Status SegmentIterator::_seek_and_peek(rowid_t rowid) {
1945
0
    {
1946
0
        _opts.stats->block_init_seek_num += 1;
1947
0
        SCOPED_RAW_TIMER(&_opts.stats->block_init_seek_ns);
1948
0
        RETURN_IF_ERROR(_seek_columns(_seek_schema->column_ids(), rowid));
1949
0
    }
1950
0
    size_t num_rows = 1;
1951
1952
    //note(wb) reset _seek_block for memory reuse
1953
    // it is easier to use row based memory layout for clear memory
1954
0
    for (int i = 0; i < _seek_block.size(); i++) {
1955
0
        _seek_block[i]->clear();
1956
0
    }
1957
0
    RETURN_IF_ERROR(_read_columns(_seek_schema->column_ids(), _seek_block, num_rows));
1958
0
    return Status::OK();
1959
0
}
1960
1961
0
Status SegmentIterator::_seek_columns(const std::vector<ColumnId>& column_ids, rowid_t pos) {
1962
0
    for (auto cid : column_ids) {
1963
0
        if (!_need_read_data(cid)) {
1964
0
            continue;
1965
0
        }
1966
0
        RETURN_IF_ERROR(_column_iterators[cid]->seek_to_ordinal(pos));
1967
0
    }
1968
0
    return Status::OK();
1969
0
}
1970
1971
/* ---------------------- for vectorization implementation  ---------------------- */
1972
1973
/**
1974
 *  For storage layer data type, can be measured from two perspectives:
1975
 *  1 Whether the type can be read in a fast way(batch read using SIMD)
1976
 *    Such as integer type and float type, this type can be read in SIMD way.
1977
 *    For the type string/bitmap/hll, they can not be read in batch way, so read this type data is slow.
1978
 *   If a type can be read fast, we can try to eliminate Lazy Materialization, because we think for this type, seek cost > read cost.
1979
 *   This is an estimate, if we want more precise cost, statistics collection is necessary(this is a todo).
1980
 *   In short, when returned non-pred columns contains string/hll/bitmap, we using Lazy Materialization.
1981
 *   Otherwise, we disable it.
1982
 *
1983
 *   When Lazy Materialization enable, we need to read column at least two times.
1984
 *   First time to read Pred col, second time to read non-pred.
1985
 *   Here's an interesting question to research, whether read Pred col once is the best plan.
1986
 *   (why not read Pred col twice or more?)
1987
 *
1988
 *   When Lazy Materialization disable, we just need to read once.
1989
 *
1990
 *
1991
 *  2 Whether the predicate type can be evaluate in a fast way(using SIMD to eval pred)
1992
 *    Such as integer type and float type, they can be eval fast.
1993
 *    But for BloomFilter/string/date, they eval slow.
1994
 *    If a type can be eval fast, we use vectorization to eval it.
1995
 *    Otherwise, we use short-circuit to eval it.
1996
 *
1997
 *
1998
 */
1999
2000
// todo(wb) need a UT here
2001
2.82k
Status SegmentIterator::_vec_init_lazy_materialization() {
2002
2.82k
    _is_pred_column.resize(_schema->columns().size(), false);
2003
2004
    // including short/vec/delete pred
2005
2.82k
    std::set<ColumnId> pred_column_ids;
2006
2.82k
    _lazy_materialization_read = false;
2007
2008
2.82k
    std::set<ColumnId> del_cond_id_set;
2009
2.82k
    _opts.delete_condition_predicates->get_all_column_ids(del_cond_id_set);
2010
2011
2.82k
    std::set<std::shared_ptr<const ColumnPredicate>> delete_predicate_set {};
2012
2.82k
    _opts.delete_condition_predicates->get_all_column_predicate(delete_predicate_set);
2013
2.82k
    for (auto predicate : delete_predicate_set) {
2014
467
        if (PredicateTypeTraits::is_range(predicate->type())) {
2015
327
            _delete_range_column_ids.push_back(predicate->column_id());
2016
327
        } else if (PredicateTypeTraits::is_bloom_filter(predicate->type())) {
2017
0
            _delete_bloom_filter_column_ids.push_back(predicate->column_id());
2018
0
        }
2019
467
    }
2020
2021
    // Step1: extract columns that can be lazy materialization
2022
2.82k
    if (!_col_predicates.empty() || !del_cond_id_set.empty()) {
2023
467
        std::set<ColumnId> short_cir_pred_col_id_set; // using set for distinct cid
2024
467
        std::set<ColumnId> vec_pred_col_id_set;
2025
2026
467
        for (auto predicate : _col_predicates) {
2027
0
            auto cid = predicate->column_id();
2028
0
            _is_pred_column[cid] = true;
2029
0
            pred_column_ids.insert(cid);
2030
2031
            // check pred using short eval or vec eval
2032
0
            if (_can_evaluated_by_vectorized(predicate)) {
2033
0
                vec_pred_col_id_set.insert(cid);
2034
0
                _pre_eval_block_predicate.push_back(predicate);
2035
0
            } else {
2036
0
                short_cir_pred_col_id_set.insert(cid);
2037
0
                _short_cir_eval_predicate.push_back(predicate);
2038
0
            }
2039
0
            if (predicate->is_runtime_filter()) {
2040
0
                _filter_info_id.push_back(predicate);
2041
0
            }
2042
0
        }
2043
2044
        // handle delete_condition
2045
467
        if (!del_cond_id_set.empty()) {
2046
467
            short_cir_pred_col_id_set.insert(del_cond_id_set.begin(), del_cond_id_set.end());
2047
467
            pred_column_ids.insert(del_cond_id_set.begin(), del_cond_id_set.end());
2048
2049
467
            for (auto cid : del_cond_id_set) {
2050
467
                _is_pred_column[cid] = true;
2051
467
            }
2052
467
        }
2053
2054
467
        _vec_pred_column_ids.assign(vec_pred_col_id_set.cbegin(), vec_pred_col_id_set.cend());
2055
467
        _short_cir_pred_column_ids.assign(short_cir_pred_col_id_set.cbegin(),
2056
467
                                          short_cir_pred_col_id_set.cend());
2057
467
    }
2058
2059
2.82k
    if (!_vec_pred_column_ids.empty()) {
2060
0
        _is_need_vec_eval = true;
2061
0
    }
2062
2.82k
    if (!_short_cir_pred_column_ids.empty()) {
2063
467
        _is_need_short_eval = true;
2064
467
    }
2065
2066
    // ColumnId to column index in block
2067
    // ColumnId will contail all columns in tablet schema, including virtual columns and global rowid column,
2068
2.82k
    _schema_block_id_map.resize(_schema->columns().size(), -1);
2069
    // Use cols read by query to initialize _schema_block_id_map.
2070
    // We need to know the index of each column in the block.
2071
    // There is an assumption here that the columns in the block are in the same order as in the read schema.
2072
    // TODO: A probelm is that, delete condition columns will exist in _schema->column_ids but not in block if
2073
    // delete column is not read by the query.
2074
9.87k
    for (int i = 0; i < _schema->num_column_ids(); i++) {
2075
7.05k
        auto cid = _schema->column_id(i);
2076
7.05k
        _schema_block_id_map[cid] = i;
2077
7.05k
    }
2078
2079
    // Step2: extract columns that can execute expr context
2080
2.82k
    _is_common_expr_column.resize(_schema->columns().size(), false);
2081
2.82k
    if (!_common_expr_ctxs_push_down.empty()) {
2082
0
        for (const auto& expr_ctx : _common_expr_ctxs_push_down) {
2083
0
            RETURN_IF_ERROR(_extract_common_expr_columns(expr_ctx->root()));
2084
0
        }
2085
0
        if (!_common_expr_columns.empty()) {
2086
0
            _is_need_expr_eval = true;
2087
0
            for (auto cid : _schema->column_ids()) {
2088
                // pred column also needs to be filtered by expr, exclude additional delete condition column.
2089
                // if delete condition column not in the block, no filter is needed
2090
                // and will be removed from _columns_to_filter in the first next_batch.
2091
0
                if (_is_common_expr_column[cid] || _is_pred_column[cid]) {
2092
0
                    auto loc = _schema_block_id_map[cid];
2093
0
                    _columns_to_filter.push_back(loc);
2094
0
                }
2095
0
            }
2096
2097
0
            for (auto pair : _vir_cid_to_idx_in_block) {
2098
0
                _columns_to_filter.push_back(cast_set<ColumnId>(pair.second));
2099
0
            }
2100
0
        }
2101
0
    }
2102
2103
    // Step 3: fill non predicate columns and second read column
2104
    // if _schema columns size equal to pred_column_ids size, lazy_materialization_read is false,
2105
    // all columns are lazy materialization columns without non predicte column.
2106
    // If common expr pushdown exists, and expr column is not contained in lazy materialization columns,
2107
    // add to second read column, which will be read after lazy materialization
2108
2.82k
    if (_schema->column_ids().size() > pred_column_ids.size()) {
2109
        // pred_column_ids maybe empty, so that could not set _lazy_materialization_read = true here
2110
        // has to check there is at least one predicate column
2111
6.99k
        for (auto cid : _schema->column_ids()) {
2112
6.99k
            if (!_is_pred_column[cid]) {
2113
6.58k
                if (_is_need_vec_eval || _is_need_short_eval) {
2114
862
                    _lazy_materialization_read = true;
2115
862
                }
2116
6.58k
                if (_is_common_expr_column[cid]) {
2117
0
                    _common_expr_column_ids.push_back(cid);
2118
6.58k
                } else {
2119
6.58k
                    _non_predicate_columns.push_back(cid);
2120
6.58k
                }
2121
6.58k
            }
2122
6.99k
        }
2123
2.76k
    }
2124
2125
    // Step 4: fill first read columns
2126
2.82k
    if (_lazy_materialization_read) {
2127
        // insert pred cid to first_read_columns
2128
410
        for (auto cid : pred_column_ids) {
2129
410
            _predicate_column_ids.push_back(cid);
2130
410
        }
2131
2.41k
    } else if (!_is_need_vec_eval && !_is_need_short_eval && !_is_need_expr_eval) {
2132
8.08k
        for (int i = 0; i < _schema->num_column_ids(); i++) {
2133
5.72k
            auto cid = _schema->column_id(i);
2134
5.72k
            _predicate_column_ids.push_back(cid);
2135
5.72k
        }
2136
2.35k
    } else {
2137
57
        if (_is_need_vec_eval || _is_need_short_eval) {
2138
            // TODO To refactor, because we suppose lazy materialization is better performance.
2139
            // pred exits, but we can eliminate lazy materialization
2140
            // insert pred/non-pred cid to first read columns
2141
57
            std::set<ColumnId> pred_id_set;
2142
57
            pred_id_set.insert(_short_cir_pred_column_ids.begin(),
2143
57
                               _short_cir_pred_column_ids.end());
2144
57
            pred_id_set.insert(_vec_pred_column_ids.begin(), _vec_pred_column_ids.end());
2145
2146
57
            DCHECK(_common_expr_column_ids.empty());
2147
            // _non_predicate_column_ids must be empty. Otherwise _lazy_materialization_read must not false.
2148
114
            for (int i = 0; i < _schema->num_column_ids(); i++) {
2149
57
                auto cid = _schema->column_id(i);
2150
57
                if (pred_id_set.find(cid) != pred_id_set.end()) {
2151
57
                    _predicate_column_ids.push_back(cid);
2152
57
                }
2153
57
            }
2154
57
        } else if (_is_need_expr_eval) {
2155
0
            DCHECK(!_is_need_vec_eval && !_is_need_short_eval);
2156
0
            for (auto cid : _common_expr_columns) {
2157
0
                _predicate_column_ids.push_back(cid);
2158
0
            }
2159
0
        }
2160
57
    }
2161
2162
2.82k
    VLOG_DEBUG << fmt::format(
2163
0
            "Laze materialization init end. "
2164
0
            "lazy_materialization_read: {}, "
2165
0
            "_col_predicates size: {}, "
2166
0
            "_cols_read_by_column_predicate: [{}], "
2167
0
            "_non_predicate_columns: [{}], "
2168
0
            "_cols_read_by_common_expr: [{}], "
2169
0
            "columns_to_filter: [{}], "
2170
0
            "_schema_block_id_map: [{}]",
2171
0
            _lazy_materialization_read, _col_predicates.size(),
2172
0
            fmt::join(_predicate_column_ids, ","), fmt::join(_non_predicate_columns, ","),
2173
0
            fmt::join(_common_expr_column_ids, ","), fmt::join(_columns_to_filter, ","),
2174
0
            fmt::join(_schema_block_id_map, ","));
2175
2.82k
    return Status::OK();
2176
2.82k
}
2177
2178
0
bool SegmentIterator::_can_evaluated_by_vectorized(std::shared_ptr<ColumnPredicate> predicate) {
2179
0
    auto cid = predicate->column_id();
2180
0
    FieldType field_type = _schema->column(cid)->type();
2181
0
    if (field_type == FieldType::OLAP_FIELD_TYPE_VARIANT) {
2182
        // Use variant cast dst type
2183
0
        field_type = _opts.target_cast_type_for_variants[_schema->column(cid)->name()]
2184
0
                             ->get_storage_field_type();
2185
0
    }
2186
0
    switch (predicate->type()) {
2187
0
    case PredicateType::EQ:
2188
0
    case PredicateType::NE:
2189
0
    case PredicateType::LE:
2190
0
    case PredicateType::LT:
2191
0
    case PredicateType::GE:
2192
0
    case PredicateType::GT: {
2193
0
        if (field_type == FieldType::OLAP_FIELD_TYPE_VARCHAR ||
2194
0
            field_type == FieldType::OLAP_FIELD_TYPE_CHAR ||
2195
0
            field_type == FieldType::OLAP_FIELD_TYPE_STRING) {
2196
0
            return config::enable_low_cardinality_optimize &&
2197
0
                   _opts.io_ctx.reader_type == ReaderType::READER_QUERY &&
2198
0
                   _column_iterators[cid]->is_all_dict_encoding();
2199
0
        } else if (field_type == FieldType::OLAP_FIELD_TYPE_DECIMAL) {
2200
0
            return false;
2201
0
        }
2202
0
        return true;
2203
0
    }
2204
0
    default:
2205
0
        return false;
2206
0
    }
2207
0
}
2208
2209
7.06k
bool SegmentIterator::_has_char_type(const TabletColumn& column_desc) {
2210
7.06k
    switch (column_desc.type()) {
2211
0
    case FieldType::OLAP_FIELD_TYPE_CHAR:
2212
0
        return true;
2213
2
    case FieldType::OLAP_FIELD_TYPE_ARRAY:
2214
2
        return _has_char_type(column_desc.get_sub_column(0));
2215
2
    case FieldType::OLAP_FIELD_TYPE_MAP:
2216
2
        return _has_char_type(column_desc.get_sub_column(0)) ||
2217
2
               _has_char_type(column_desc.get_sub_column(1));
2218
0
    case FieldType::OLAP_FIELD_TYPE_STRUCT:
2219
0
        for (uint32_t idx = 0; idx < column_desc.get_subtype_count(); ++idx) {
2220
0
            if (_has_char_type(column_desc.get_sub_column(idx))) {
2221
0
                return true;
2222
0
            }
2223
0
        }
2224
0
        return false;
2225
7.05k
    default:
2226
7.05k
        return false;
2227
7.06k
    }
2228
7.06k
};
2229
2230
2.82k
void SegmentIterator::_vec_init_char_column_id(Block* block) {
2231
2.82k
    if (!_char_type_idx.empty()) {
2232
0
        return;
2233
0
    }
2234
2.82k
    _is_char_type.resize(_schema->columns().size(), false);
2235
9.87k
    for (size_t i = 0; i < _schema->num_column_ids(); i++) {
2236
7.05k
        auto cid = _schema->column_id(i);
2237
7.05k
        const TabletColumn* column_desc = _schema->column(cid);
2238
2239
        // The additional deleted filter condition will be in the materialized column at the end of the block.
2240
        // After _output_column_by_sel_idx, it will be erased, so we do not need to shrink it.
2241
7.05k
        if (i < block->columns()) {
2242
7.05k
            if (_has_char_type(*column_desc)) {
2243
0
                _char_type_idx.emplace_back(i);
2244
0
            }
2245
7.05k
        }
2246
2247
7.05k
        if (column_desc->type() == FieldType::OLAP_FIELD_TYPE_CHAR) {
2248
0
            _is_char_type[cid] = true;
2249
0
        }
2250
7.05k
    }
2251
2.82k
}
2252
2253
bool SegmentIterator::_prune_column(ColumnId cid, MutableColumnPtr& column, bool fill_defaults,
2254
27.1k
                                    size_t num_of_defaults) {
2255
27.1k
    if (_need_read_data(cid)) {
2256
27.1k
        return false;
2257
27.1k
    }
2258
0
    if (!fill_defaults) {
2259
0
        return true;
2260
0
    }
2261
0
    if (column->is_nullable()) {
2262
0
        auto nullable_col_ptr = reinterpret_cast<ColumnNullable*>(column.get());
2263
0
        nullable_col_ptr->get_null_map_column().insert_many_defaults(num_of_defaults);
2264
0
        nullable_col_ptr->get_nested_column_ptr()->insert_many_defaults(num_of_defaults);
2265
0
    } else {
2266
        // assert(column->is_const());
2267
0
        column->insert_many_defaults(num_of_defaults);
2268
0
    }
2269
0
    return true;
2270
0
}
2271
2272
Status SegmentIterator::_read_columns(const std::vector<ColumnId>& column_ids,
2273
0
                                      MutableColumns& column_block, size_t nrows) {
2274
0
    for (auto cid : column_ids) {
2275
0
        auto& column = column_block[cid];
2276
0
        size_t rows_read = nrows;
2277
0
        if (_prune_column(cid, column, true, rows_read)) {
2278
0
            continue;
2279
0
        }
2280
0
        RETURN_IF_ERROR(_column_iterators[cid]->next_batch(&rows_read, column));
2281
0
        if (nrows != rows_read) {
2282
0
            return Status::Error<ErrorCode::INTERNAL_ERROR>("nrows({}) != rows_read({})", nrows,
2283
0
                                                            rows_read);
2284
0
        }
2285
0
    }
2286
0
    return Status::OK();
2287
0
}
2288
2289
Status SegmentIterator::_init_current_block(Block* block,
2290
                                            std::vector<MutableColumnPtr>& current_columns,
2291
12.9k
                                            uint32_t nrows_read_limit) {
2292
12.9k
    block->clear_column_data(_schema->num_column_ids());
2293
2294
40.9k
    for (size_t i = 0; i < _schema->num_column_ids(); i++) {
2295
28.0k
        auto cid = _schema->column_id(i);
2296
28.0k
        const auto* column_desc = _schema->column(cid);
2297
2298
28.0k
        auto file_column_type = _storage_name_and_type[cid].second;
2299
28.0k
        auto expected_type = Schema::get_data_type_ptr(*column_desc);
2300
28.0k
        if (!_is_pred_column[cid] && !file_column_type->equals(*expected_type)) {
2301
            // The storage layer type is different from schema needed type, so we use storage
2302
            // type to read columns instead of schema type for safety
2303
0
            VLOG_DEBUG << fmt::format(
2304
0
                    "Recreate column with expected type {}, file column type {}, col_name {}, "
2305
0
                    "col_path {}",
2306
0
                    block->get_by_position(i).type->get_name(), file_column_type->get_name(),
2307
0
                    column_desc->name(),
2308
0
                    column_desc->path_info_ptr() == nullptr
2309
0
                            ? ""
2310
0
                            : column_desc->path_info_ptr()->get_path());
2311
            // TODO reuse
2312
0
            current_columns[cid] = file_column_type->create_column();
2313
0
            current_columns[cid]->reserve(nrows_read_limit);
2314
28.0k
        } else {
2315
            // the column in block must clear() here to insert new data
2316
28.0k
            if (_is_pred_column[cid] ||
2317
28.0k
                i >= block->columns()) { //todo(wb) maybe we can release it after output block
2318
2.16k
                if (current_columns[cid].get() == nullptr) {
2319
0
                    return Status::InternalError(
2320
0
                            "SegmentIterator meet invalid column, id={}, name={}", cid,
2321
0
                            _schema->column(cid)->name());
2322
0
                }
2323
2.16k
                current_columns[cid]->clear();
2324
25.9k
            } else { // non-predicate column
2325
25.9k
                current_columns[cid] = std::move(*block->get_by_position(i).column).mutate();
2326
25.9k
                current_columns[cid]->reserve(nrows_read_limit);
2327
25.9k
            }
2328
28.0k
        }
2329
28.0k
    }
2330
2331
12.9k
    for (auto entry : _virtual_column_exprs) {
2332
0
        auto cid = entry.first;
2333
0
        current_columns[cid] = ColumnNothing::create(0);
2334
0
        current_columns[cid]->reserve(nrows_read_limit);
2335
0
    }
2336
2337
12.9k
    return Status::OK();
2338
12.9k
}
2339
2340
10.1k
Status SegmentIterator::_output_non_pred_columns(Block* block) {
2341
10.1k
    SCOPED_RAW_TIMER(&_opts.stats->output_col_ns);
2342
10.1k
    VLOG_DEBUG << fmt::format(
2343
0
            "Output non-predicate columns, _non_predicate_columns: [{}], "
2344
0
            "_schema_block_id_map: [{}]",
2345
0
            fmt::join(_non_predicate_columns, ","), fmt::join(_schema_block_id_map, ","));
2346
10.1k
    RETURN_IF_ERROR(_convert_to_expected_type(_non_predicate_columns));
2347
19.3k
    for (auto cid : _non_predicate_columns) {
2348
19.3k
        auto loc = _schema_block_id_map[cid];
2349
        // Whether a delete predicate column gets output depends on how the caller builds
2350
        // the block passed to next_batch(). Both calling paths now build the block with
2351
        // only the output schema (return_columns), so delete predicate columns are skipped:
2352
        //
2353
        // 1) VMergeIterator path: block_reset() builds _block using the output schema
2354
        //    (return_columns only), e.g. block has 2 columns {c1, c2}.
2355
        //    Here loc=2 for delete predicate c3, block->columns()=2, so loc < block->columns()
2356
        //    is false, and c3 is skipped.
2357
        //
2358
        // 2) VUnionIterator path: the caller's block is built with only return_columns
2359
        //    (output schema), e.g. block has 2 columns {c1, c2}.
2360
        //    Here loc=2 for c3, block->columns()=2, so loc < block->columns() is false,
2361
        //    and c3 is skipped — same behavior as the VMergeIterator path.
2362
19.3k
        if (loc < block->columns()) {
2363
19.3k
            bool column_in_block_is_nothing = check_and_get_column<const ColumnNothing>(
2364
19.3k
                    block->get_by_position(loc).column.get());
2365
19.3k
            bool column_is_normal = !_vir_cid_to_idx_in_block.contains(cid);
2366
19.3k
            bool return_column_is_nothing =
2367
19.3k
                    check_and_get_column<const ColumnNothing>(_current_return_columns[cid].get());
2368
19.3k
            VLOG_DEBUG << fmt::format(
2369
0
                    "Cid {} loc {}, column_in_block_is_nothing {}, column_is_normal {}, "
2370
0
                    "return_column_is_nothing {}",
2371
0
                    cid, loc, column_in_block_is_nothing, column_is_normal,
2372
0
                    return_column_is_nothing);
2373
2374
19.3k
            if (column_in_block_is_nothing || column_is_normal) {
2375
19.3k
                block->replace_by_position(loc, std::move(_current_return_columns[cid]));
2376
19.3k
                VLOG_DEBUG << fmt::format(
2377
0
                        "Output non-predicate column, cid: {}, loc: {}, col_name: {}, rows {}", cid,
2378
0
                        loc, _schema->column(cid)->name(),
2379
0
                        block->get_by_position(loc).column->size());
2380
19.3k
            }
2381
            // Means virtual column in block has been materialized(maybe by common expr).
2382
            // so do nothing here.
2383
19.3k
        }
2384
19.3k
    }
2385
10.1k
    return Status::OK();
2386
10.1k
}
2387
2388
/**
2389
 * Reads columns by their index, handling both continuous and discontinuous rowid scenarios.
2390
 *
2391
 * This function is designed to read a specified number of rows (up to nrows_read_limit)
2392
 * from the segment iterator, dealing with both continuous and discontinuous rowid arrays.
2393
 * It operates as follows:
2394
 *
2395
 * 1. Reads a batch of rowids (up to the specified limit), and checks if they are continuous.
2396
 *    Continuous here means that the rowids form an unbroken sequence (e.g., 1, 2, 3, 4...).
2397
 *
2398
 * 2. For each column that needs to be read (identified by _predicate_column_ids):
2399
 *    - If the rowids are continuous, the function uses seek_to_ordinal and next_batch
2400
 *      for efficient reading.
2401
 *    - If the rowids are not continuous, the function processes them in smaller batches
2402
 *      (each of size up to 256). Each batch is checked for internal continuity:
2403
 *        a. If a batch is continuous, uses seek_to_ordinal and next_batch for that batch.
2404
 *        b. If a batch is not continuous, uses read_by_rowids for individual rowids in the batch.
2405
 *
2406
 * This approach optimizes reading performance by leveraging batch processing for continuous
2407
 * rowid sequences and handling discontinuities gracefully in smaller chunks.
2408
 */
2409
12.9k
Status SegmentIterator::_read_columns_by_index(uint32_t nrows_read_limit, uint16_t& nrows_read) {
2410
12.9k
    SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_ns);
2411
2412
12.9k
    nrows_read = (uint16_t)_range_iter->read_batch_rowids(_block_rowids.data(), nrows_read_limit);
2413
12.9k
    bool is_continuous = (nrows_read > 1) &&
2414
12.9k
                         (_block_rowids[nrows_read - 1] - _block_rowids[0] == nrows_read - 1);
2415
12.9k
    VLOG_DEBUG << fmt::format(
2416
0
            "nrows_read from range iterator: {}, is_continus {}, _cols_read_by_column_predicate "
2417
0
            "[{}]",
2418
0
            nrows_read, is_continuous, fmt::join(_predicate_column_ids, ","));
2419
2420
12.9k
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
2421
0
            "[verbose] SegmentIterator::_read_columns_by_index read {} rowids, continuous: {}, "
2422
0
            "rowids: [{}...{}]",
2423
0
            nrows_read, is_continuous, nrows_read > 0 ? _block_rowids[0] : 0,
2424
0
            nrows_read > 0 ? _block_rowids[nrows_read - 1] : 0);
2425
25.0k
    for (auto cid : _predicate_column_ids) {
2426
25.0k
        auto& column = _current_return_columns[cid];
2427
25.0k
        VLOG_DEBUG << fmt::format("Reading column {}, col_name {}", cid,
2428
0
                                  _schema->column(cid)->name());
2429
25.0k
        if (!_virtual_column_exprs.contains(cid)) {
2430
25.0k
            if (_no_need_read_key_data(cid, column, nrows_read)) {
2431
0
                VLOG_DEBUG << fmt::format("Column {} no need to read.", cid);
2432
0
                continue;
2433
0
            }
2434
25.0k
            if (_prune_column(cid, column, true, nrows_read)) {
2435
0
                VLOG_DEBUG << fmt::format("Column {} is pruned. No need to read data.", cid);
2436
0
                continue;
2437
0
            }
2438
25.0k
            DBUG_EXECUTE_IF("segment_iterator._read_columns_by_index", {
2439
25.0k
                auto col_name = _opts.tablet_schema->column(cid).name();
2440
25.0k
                auto debug_col_name =
2441
25.0k
                        DebugPoints::instance()->get_debug_param_or_default<std::string>(
2442
25.0k
                                "segment_iterator._read_columns_by_index", "column_name", "");
2443
25.0k
                if (debug_col_name.empty() && col_name != "__DORIS_DELETE_SIGN__") {
2444
25.0k
                    return Status::Error<ErrorCode::INTERNAL_ERROR>(
2445
25.0k
                            "does not need to read data, {}", col_name);
2446
25.0k
                }
2447
25.0k
                if (debug_col_name.find(col_name) != std::string::npos) {
2448
25.0k
                    return Status::Error<ErrorCode::INTERNAL_ERROR>(
2449
25.0k
                            "does not need to read data, {}", col_name);
2450
25.0k
                }
2451
25.0k
            })
2452
25.0k
        }
2453
2454
25.0k
        if (is_continuous) {
2455
18.5k
            size_t rows_read = nrows_read;
2456
18.5k
            _opts.stats->predicate_column_read_seek_num += 1;
2457
18.5k
            if (_opts.runtime_state && _opts.runtime_state->enable_profile()) {
2458
0
                SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_seek_ns);
2459
0
                RETURN_IF_ERROR(_column_iterators[cid]->seek_to_ordinal(_block_rowids[0]));
2460
18.5k
            } else {
2461
18.5k
                RETURN_IF_ERROR(_column_iterators[cid]->seek_to_ordinal(_block_rowids[0]));
2462
18.5k
            }
2463
18.5k
            RETURN_IF_ERROR(_column_iterators[cid]->next_batch(&rows_read, column));
2464
18.5k
            if (rows_read != nrows_read) {
2465
0
                return Status::Error<ErrorCode::INTERNAL_ERROR>("nrows({}) != rows_read({})",
2466
0
                                                                nrows_read, rows_read);
2467
0
            }
2468
18.5k
        } else {
2469
6.50k
            const uint32_t batch_size = _range_iter->get_batch_size();
2470
6.50k
            uint32_t processed = 0;
2471
7.69k
            while (processed < nrows_read) {
2472
1.19k
                uint32_t current_batch_size = std::min(batch_size, nrows_read - processed);
2473
1.19k
                bool batch_continuous = (current_batch_size > 1) &&
2474
1.19k
                                        (_block_rowids[processed + current_batch_size - 1] -
2475
1.17k
                                                 _block_rowids[processed] ==
2476
1.17k
                                         current_batch_size - 1);
2477
2478
1.19k
                if (batch_continuous) {
2479
0
                    size_t rows_read = current_batch_size;
2480
0
                    _opts.stats->predicate_column_read_seek_num += 1;
2481
0
                    if (_opts.runtime_state && _opts.runtime_state->enable_profile()) {
2482
0
                        SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_seek_ns);
2483
0
                        RETURN_IF_ERROR(
2484
0
                                _column_iterators[cid]->seek_to_ordinal(_block_rowids[processed]));
2485
0
                    } else {
2486
0
                        RETURN_IF_ERROR(
2487
0
                                _column_iterators[cid]->seek_to_ordinal(_block_rowids[processed]));
2488
0
                    }
2489
0
                    RETURN_IF_ERROR(_column_iterators[cid]->next_batch(&rows_read, column));
2490
0
                    if (rows_read != current_batch_size) {
2491
0
                        return Status::Error<ErrorCode::INTERNAL_ERROR>(
2492
0
                                "batch nrows({}) != rows_read({})", current_batch_size, rows_read);
2493
0
                    }
2494
1.19k
                } else {
2495
1.19k
                    RETURN_IF_ERROR(_column_iterators[cid]->read_by_rowids(
2496
1.19k
                            &_block_rowids[processed], current_batch_size, column));
2497
1.19k
                }
2498
1.19k
                processed += current_batch_size;
2499
1.19k
            }
2500
6.50k
        }
2501
25.0k
    }
2502
2503
12.9k
    return Status::OK();
2504
12.9k
}
2505
void SegmentIterator::_replace_version_col_if_needed(const std::vector<ColumnId>& column_ids,
2506
14.3k
                                                     size_t num_rows) {
2507
    // Only the rowset with single version need to replace the version column.
2508
    // Doris can't determine the version before publish_version finished, so
2509
    // we can't write data to __DORIS_VERSION_COL__ in segment writer, the value
2510
    // is 0 by default.
2511
    // So we need to replace the value to real version while reading.
2512
14.3k
    if (_opts.version.first != _opts.version.second) {
2513
6.49k
        return;
2514
6.49k
    }
2515
7.81k
    int32_t version_idx = _schema->version_col_idx();
2516
7.81k
    if (std::ranges::find(column_ids, version_idx) == column_ids.end()) {
2517
7.81k
        return;
2518
7.81k
    }
2519
2520
0
    const auto* column_desc = _schema->column(version_idx);
2521
0
    auto column = Schema::get_data_type_ptr(*column_desc)->create_column();
2522
0
    DCHECK(_schema->column(version_idx)->type() == FieldType::OLAP_FIELD_TYPE_BIGINT);
2523
0
    auto* col_ptr = assert_cast<ColumnInt64*>(column.get());
2524
0
    for (size_t j = 0; j < num_rows; j++) {
2525
0
        col_ptr->insert_value(_opts.version.second);
2526
0
    }
2527
0
    _current_return_columns[version_idx] = std::move(column);
2528
0
    VLOG_DEBUG << "replaced version column in segment iterator, version_col_idx:" << version_idx;
2529
0
}
2530
2531
void SegmentIterator::_update_lsn_col_if_needed(const std::vector<ColumnId>& column_ids,
2532
14.3k
                                                size_t num_rows) {
2533
    // | commit tso(64) | auto-inc row_id(64) |
2534
14.3k
    if (_opts.version.first != _opts.version.second) {
2535
6.49k
        return;
2536
6.49k
    }
2537
2538
7.81k
    if (_opts.io_ctx.reader_type != ReaderType::READER_BINLOG &&
2539
7.81k
        _opts.io_ctx.reader_type != ReaderType::READER_BINLOG_COMPACTION) {
2540
7.81k
        return;
2541
7.81k
    }
2542
2543
0
    int32_t lsn_col_idx = _schema->lsn_col_idx();
2544
0
    if (lsn_col_idx < 0 || std::ranges::find(column_ids, lsn_col_idx) == column_ids.end()) {
2545
0
        return;
2546
0
    }
2547
2548
0
    DCHECK_EQ(_opts.commit_tso.start_tso(), _opts.commit_tso.end_tso());
2549
0
    const Int64 commit_tso = _opts.commit_tso.end_tso() == -1 ? 0 : _opts.commit_tso.end_tso();
2550
2551
0
    if (_is_pred_column[lsn_col_idx]) {
2552
0
        auto* lsn_column = assert_cast<PredicateColumnType<TYPE_LARGEINT>*>(
2553
0
                _current_return_columns[lsn_col_idx].get());
2554
0
        std::vector<Int128> binlog_lsns;
2555
0
        binlog_lsns.reserve(num_rows);
2556
0
        for (size_t j = 0; j < num_rows; j++) {
2557
0
            const Int128 row_id = lsn_column->get_data()[j];
2558
0
            binlog_lsns.emplace_back(make_row_binlog_lsn(commit_tso, row_id));
2559
0
        }
2560
0
        _current_return_columns[lsn_col_idx]->clear();
2561
0
        for (const auto& binlog_lsn : binlog_lsns) {
2562
0
            lsn_column->insert_data(reinterpret_cast<const char*>(&binlog_lsn), 0);
2563
0
        }
2564
0
        return;
2565
0
    }
2566
2567
0
    auto* lsn_column = assert_cast<ColumnInt128*>(_current_return_columns[lsn_col_idx].get());
2568
0
    const auto* column_desc = _schema->column(lsn_col_idx);
2569
0
    auto column = Schema::get_data_type_ptr(*column_desc)->create_column();
2570
0
    DCHECK(column_desc->type() == FieldType::OLAP_FIELD_TYPE_LARGEINT);
2571
0
    auto* col_ptr = assert_cast<ColumnInt128*>(column.get());
2572
2573
0
    for (size_t j = 0; j < num_rows; j++) {
2574
0
        const Int128 row_id = lsn_column->get_element(j);
2575
0
        col_ptr->insert_value(make_row_binlog_lsn(commit_tso, row_id));
2576
0
    }
2577
0
    _current_return_columns[lsn_col_idx] = std::move(column);
2578
0
}
2579
2580
void SegmentIterator::_update_tso_col_if_needed(const std::vector<ColumnId>& column_ids,
2581
14.3k
                                                size_t num_rows) {
2582
    // use physical time part of commit tso to replace timestamp col
2583
14.3k
    if (_opts.version.first != _opts.version.second) {
2584
6.49k
        return;
2585
6.49k
    }
2586
2587
7.81k
    if (_opts.io_ctx.reader_type != ReaderType::READER_BINLOG &&
2588
7.81k
        _opts.io_ctx.reader_type != ReaderType::READER_BINLOG_COMPACTION) {
2589
7.81k
        return;
2590
7.81k
    }
2591
2592
0
    int32_t tso_col_idx = _schema->tso_col_idx();
2593
0
    if (tso_col_idx < 0 || std::ranges::find(column_ids, tso_col_idx) == column_ids.end()) {
2594
0
        return;
2595
0
    }
2596
2597
0
    DCHECK_EQ(_opts.commit_tso.start_tso(), _opts.commit_tso.end_tso());
2598
0
    Int64 commit_tso = _opts.commit_tso.end_tso() == -1 ? 0 : _opts.commit_tso.end_tso();
2599
0
    Int64 commit_time = extract_tso_physical_time(commit_tso);
2600
2601
0
    if (_is_pred_column[tso_col_idx]) {
2602
        // Nullable predicate column is represented as ColumnNullable(predicate_col)
2603
0
        if (auto* tso_nullable =
2604
0
                    typeid_cast<ColumnNullable*>(_current_return_columns[tso_col_idx].get())) {
2605
0
            _current_return_columns[tso_col_idx]->clear();
2606
0
            auto value = commit_time;
2607
0
            for (size_t j = 0; j < num_rows; j++) {
2608
0
                tso_nullable->get_nested_column_ptr()->insert_data(
2609
0
                        reinterpret_cast<const char*>(&value), 0);
2610
0
                tso_nullable->get_null_map_data().emplace_back(0);
2611
0
            }
2612
0
            return;
2613
0
        }
2614
2615
0
        auto* tso_column = assert_cast<PredicateColumnType<TYPE_BIGINT>*>(
2616
0
                _current_return_columns[tso_col_idx].get());
2617
0
        _current_return_columns[tso_col_idx]->clear();
2618
0
        auto value = commit_time;
2619
0
        for (size_t j = 0; j < num_rows; j++) {
2620
0
            tso_column->insert_data(reinterpret_cast<const char*>(&value), 0);
2621
0
        }
2622
0
        return;
2623
0
    }
2624
2625
0
    const auto* column_desc = _schema->column(tso_col_idx);
2626
0
    auto column = Schema::get_data_type_ptr(*column_desc)->create_column();
2627
0
    DCHECK(column_desc->type() == FieldType::OLAP_FIELD_TYPE_BIGINT);
2628
2629
0
    if (auto* tso_nullable = typeid_cast<ColumnNullable*>(column.get())) {
2630
0
        auto* col_ptr = assert_cast<ColumnInt64*>(&tso_nullable->get_nested_column());
2631
0
        for (size_t j = 0; j < num_rows; j++) {
2632
0
            col_ptr->insert_value(commit_time);
2633
0
            tso_nullable->get_null_map_data().emplace_back(0);
2634
0
        }
2635
0
    } else {
2636
0
        auto* col_ptr = assert_cast<ColumnInt64*>(column.get());
2637
0
        for (size_t j = 0; j < num_rows; j++) {
2638
0
            col_ptr->insert_value(commit_time);
2639
0
        }
2640
0
    }
2641
0
    _current_return_columns[tso_col_idx] = std::move(column);
2642
0
}
2643
2644
uint16_t SegmentIterator::_evaluate_vectorization_predicate(uint16_t* sel_rowid_idx,
2645
1.69k
                                                            uint16_t selected_size) {
2646
1.69k
    SCOPED_RAW_TIMER(&_opts.stats->vec_cond_ns);
2647
1.69k
    bool all_pred_always_true = true;
2648
1.69k
    for (const auto& pred : _pre_eval_block_predicate) {
2649
0
        if (!pred->always_true()) {
2650
0
            all_pred_always_true = false;
2651
0
        } else {
2652
0
            pred->update_filter_info(0, 0, selected_size);
2653
0
        }
2654
0
    }
2655
2656
1.69k
    const uint16_t original_size = selected_size;
2657
    //If all predicates are always_true, then return directly.
2658
1.69k
    if (all_pred_always_true || !_is_need_vec_eval) {
2659
3.90M
        for (uint16_t i = 0; i < original_size; ++i) {
2660
3.90M
            sel_rowid_idx[i] = i;
2661
3.90M
        }
2662
        // All preds are always_true, so return immediately and update the profile statistics here.
2663
1.69k
        _opts.stats->vec_cond_input_rows += original_size;
2664
1.69k
        return original_size;
2665
1.69k
    }
2666
2667
0
    _ret_flags.resize(original_size);
2668
0
    DCHECK(!_pre_eval_block_predicate.empty());
2669
0
    bool is_first = true;
2670
0
    for (auto& pred : _pre_eval_block_predicate) {
2671
0
        if (pred->always_true()) {
2672
0
            continue;
2673
0
        }
2674
0
        auto column_id = pred->column_id();
2675
0
        auto& column = _current_return_columns[column_id];
2676
0
        if (is_first) {
2677
0
            pred->evaluate_vec(*column, original_size, (bool*)_ret_flags.data());
2678
0
            is_first = false;
2679
0
        } else {
2680
0
            pred->evaluate_and_vec(*column, original_size, (bool*)_ret_flags.data());
2681
0
        }
2682
0
    }
2683
2684
0
    uint16_t new_size = 0;
2685
2686
0
    uint16_t sel_pos = 0;
2687
0
    const uint16_t sel_end = sel_pos + selected_size;
2688
0
    static constexpr size_t SIMD_BYTES = simd::bits_mask_length();
2689
0
    const uint16_t sel_end_simd = sel_pos + selected_size / SIMD_BYTES * SIMD_BYTES;
2690
2691
0
    while (sel_pos < sel_end_simd) {
2692
0
        auto mask = simd::bytes_mask_to_bits_mask(_ret_flags.data() + sel_pos);
2693
0
        if (0 == mask) {
2694
            //pass
2695
0
        } else if (simd::bits_mask_all() == mask) {
2696
0
            for (uint16_t i = 0; i < SIMD_BYTES; i++) {
2697
0
                sel_rowid_idx[new_size++] = sel_pos + i;
2698
0
            }
2699
0
        } else {
2700
0
            simd::iterate_through_bits_mask(
2701
0
                    [&](const int bit_pos) {
2702
0
                        sel_rowid_idx[new_size++] = sel_pos + (uint16_t)bit_pos;
2703
0
                    },
2704
0
                    mask);
2705
0
        }
2706
0
        sel_pos += SIMD_BYTES;
2707
0
    }
2708
2709
0
    for (; sel_pos < sel_end; sel_pos++) {
2710
0
        if (_ret_flags[sel_pos]) {
2711
0
            sel_rowid_idx[new_size++] = sel_pos;
2712
0
        }
2713
0
    }
2714
2715
0
    _opts.stats->vec_cond_input_rows += original_size;
2716
0
    _opts.stats->rows_vec_cond_filtered += original_size - new_size;
2717
0
    return new_size;
2718
1.69k
}
2719
2720
uint16_t SegmentIterator::_evaluate_short_circuit_predicate(uint16_t* vec_sel_rowid_idx,
2721
1.69k
                                                            uint16_t selected_size) {
2722
1.69k
    SCOPED_RAW_TIMER(&_opts.stats->short_cond_ns);
2723
1.69k
    if (!_is_need_short_eval) {
2724
0
        return selected_size;
2725
0
    }
2726
2727
1.69k
    uint16_t original_size = selected_size;
2728
1.69k
    for (auto predicate : _short_cir_eval_predicate) {
2729
0
        auto column_id = predicate->column_id();
2730
0
        auto& short_cir_column = _current_return_columns[column_id];
2731
0
        selected_size = predicate->evaluate(*short_cir_column, vec_sel_rowid_idx, selected_size);
2732
0
    }
2733
2734
1.69k
    _opts.stats->short_circuit_cond_input_rows += original_size;
2735
1.69k
    _opts.stats->rows_short_circuit_cond_filtered += original_size - selected_size;
2736
2737
    // evaluate delete condition
2738
1.69k
    original_size = selected_size;
2739
1.69k
    selected_size = _opts.delete_condition_predicates->evaluate(_current_return_columns,
2740
1.69k
                                                                vec_sel_rowid_idx, selected_size);
2741
1.69k
    _opts.stats->rows_vec_del_cond_filtered += original_size - selected_size;
2742
1.69k
    return selected_size;
2743
1.69k
}
2744
2745
1
static void shrink_materialized_block_columns(Block* block, size_t rows) {
2746
2
    for (auto& entry : *block) {
2747
2
        if (entry.column && entry.column->size() > rows) {
2748
1
            entry.column = entry.column->shrink(rows);
2749
1
        }
2750
2
    }
2751
1
}
2752
2753
static void slice_materialized_block_columns(Block* block, size_t offset, size_t rows,
2754
1
                                             size_t original_rows) {
2755
1
    for (auto& entry : *block) {
2756
1
        if (!entry.column || entry.column->size() == 0) {
2757
0
            continue;
2758
0
        }
2759
1
        DORIS_CHECK(entry.column->size() == original_rows);
2760
1
        entry.column = entry.column->cut(offset, rows);
2761
1
    }
2762
1
}
2763
2764
1.69k
Status SegmentIterator::_apply_read_limit_to_selected_rows(Block* block, uint16_t& selected_size) {
2765
1.69k
    if (_opts.read_limit == 0) {
2766
1.69k
        return Status::OK();
2767
1.69k
    }
2768
2
    DORIS_CHECK(_rows_returned <= _opts.read_limit);
2769
2
    size_t remaining = _opts.read_limit - _rows_returned;
2770
2
    if (remaining == 0) {
2771
0
        selected_size = 0;
2772
0
        shrink_materialized_block_columns(block, 0);
2773
0
        return Status::OK();
2774
0
    }
2775
2
    if (selected_size > remaining) {
2776
2
        if (_opts.read_orderby_key_reverse) {
2777
1
            const auto original_size = selected_size;
2778
1
            const auto offset = original_size - remaining;
2779
21
            for (size_t i = 0; i < remaining; ++i) {
2780
20
                _sel_rowid_idx[i] = _sel_rowid_idx[offset + i];
2781
20
            }
2782
1
            selected_size = cast_set<uint16_t>(remaining);
2783
1
            slice_materialized_block_columns(block, offset, remaining, original_size);
2784
1
            return Status::OK();
2785
1
        }
2786
1
        selected_size = cast_set<uint16_t>(remaining);
2787
1
        shrink_materialized_block_columns(block, selected_size);
2788
1
    }
2789
1
    return Status::OK();
2790
2
}
2791
2792
Status SegmentIterator::_read_columns_by_rowids(std::vector<ColumnId>& read_column_ids,
2793
                                                std::vector<rowid_t>& rowid_vector,
2794
                                                uint16_t* sel_rowid_idx, size_t select_size,
2795
                                                MutableColumns* mutable_columns,
2796
1.38k
                                                bool init_condition_cache) {
2797
1.38k
    SCOPED_RAW_TIMER(&_opts.stats->lazy_read_ns);
2798
1.38k
    std::vector<rowid_t> rowids(select_size);
2799
2800
1.38k
    if (init_condition_cache) {
2801
0
        DCHECK(_condition_cache);
2802
0
        auto& condition_cache = *_condition_cache;
2803
0
        for (size_t i = 0; i < select_size; ++i) {
2804
0
            rowids[i] = rowid_vector[sel_rowid_idx[i]];
2805
0
            condition_cache[rowids[i] / SegmentIterator::CONDITION_CACHE_OFFSET] = true;
2806
0
        }
2807
1.38k
    } else {
2808
2.74M
        for (size_t i = 0; i < select_size; ++i) {
2809
2.74M
            rowids[i] = rowid_vector[sel_rowid_idx[i]];
2810
2.74M
        }
2811
1.38k
    }
2812
2813
2.10k
    for (auto cid : read_column_ids) {
2814
2.10k
        auto& colunm = (*mutable_columns)[cid];
2815
2.10k
        if (_no_need_read_key_data(cid, colunm, select_size)) {
2816
0
            continue;
2817
0
        }
2818
2.10k
        if (_prune_column(cid, colunm, true, select_size)) {
2819
0
            continue;
2820
0
        }
2821
2822
2.10k
        DBUG_EXECUTE_IF("segment_iterator._read_columns_by_index", {
2823
2.10k
            auto debug_col_name = DebugPoints::instance()->get_debug_param_or_default<std::string>(
2824
2.10k
                    "segment_iterator._read_columns_by_index", "column_name", "");
2825
2.10k
            if (debug_col_name.empty()) {
2826
2.10k
                return Status::Error<ErrorCode::INTERNAL_ERROR>("does not need to read data");
2827
2.10k
            }
2828
2.10k
            auto col_name = _opts.tablet_schema->column(cid).name();
2829
2.10k
            if (debug_col_name.find(col_name) != std::string::npos) {
2830
2.10k
                return Status::Error<ErrorCode::INTERNAL_ERROR>("does not need to read data, {}",
2831
2.10k
                                                                debug_col_name);
2832
2.10k
            }
2833
2.10k
        })
2834
2835
2.10k
        if (_current_return_columns[cid].get() == nullptr) {
2836
0
            return Status::InternalError(
2837
0
                    "SegmentIterator meet invalid column, return columns size {}, cid {}",
2838
0
                    _current_return_columns.size(), cid);
2839
0
        }
2840
2.10k
        RETURN_IF_ERROR(_column_iterators[cid]->read_by_rowids(rowids.data(), select_size,
2841
2.10k
                                                               _current_return_columns[cid]));
2842
2.10k
    }
2843
2844
1.38k
    return Status::OK();
2845
1.38k
}
2846
2847
12.9k
Status SegmentIterator::next_batch(Block* block) {
2848
    // Replace virtual columns with ColumnNothing at the begining of each next_batch call.
2849
12.9k
    _init_virtual_columns(block);
2850
12.9k
    auto status = [&]() {
2851
12.9k
        RETURN_IF_CATCH_EXCEPTION({
2852
            // Adaptive batch size: predict how many rows this batch should read.
2853
12.9k
            if (_block_size_predictor) {
2854
12.9k
                auto predicted = static_cast<uint32_t>(_block_size_predictor->predict_next_rows());
2855
12.9k
                _opts.block_row_max = std::min(predicted, _initial_block_row_max);
2856
12.9k
                _opts.stats->adaptive_batch_size_predict_min_rows =
2857
12.9k
                        std::min(_opts.stats->adaptive_batch_size_predict_min_rows,
2858
12.9k
                                 static_cast<int64_t>(predicted));
2859
12.9k
                _opts.stats->adaptive_batch_size_predict_max_rows =
2860
12.9k
                        std::max(_opts.stats->adaptive_batch_size_predict_max_rows,
2861
12.9k
                                 static_cast<int64_t>(predicted));
2862
12.9k
            } else {
2863
                // No predictor — record the fixed batch size using min/max so we don't
2864
                // clobber values already accumulated by other segment iterators that
2865
                // share the same OlapReaderStatistics.
2866
12.9k
                _opts.stats->adaptive_batch_size_predict_min_rows =
2867
12.9k
                        std::min(_opts.stats->adaptive_batch_size_predict_min_rows,
2868
12.9k
                                 static_cast<int64_t>(_opts.block_row_max));
2869
12.9k
                _opts.stats->adaptive_batch_size_predict_max_rows =
2870
12.9k
                        std::max(_opts.stats->adaptive_batch_size_predict_max_rows,
2871
12.9k
                                 static_cast<int64_t>(_opts.block_row_max));
2872
12.9k
            }
2873
2874
12.9k
            auto res = _next_batch_internal(block);
2875
2876
12.9k
            if (res.is<END_OF_FILE>()) {
2877
                // Since we have a type check at the caller.
2878
                // So a replacement of nothing column with real column is needed.
2879
12.9k
                const auto& idx_to_datatype = _opts.vir_col_idx_to_type;
2880
12.9k
                for (const auto& pair : _vir_cid_to_idx_in_block) {
2881
12.9k
                    size_t idx = pair.second;
2882
12.9k
                    auto type = idx_to_datatype.find(idx)->second;
2883
12.9k
                    block->replace_by_position(idx, type->create_column());
2884
12.9k
                }
2885
2886
12.9k
                if (_opts.condition_cache_digest && !_find_condition_cache) {
2887
12.9k
                    auto* condition_cache = ConditionCache::instance();
2888
12.9k
                    ConditionCache::CacheKey cache_key(_opts.rowset_id, _segment->id(),
2889
12.9k
                                                       _opts.condition_cache_digest);
2890
12.9k
                    VLOG_DEBUG << "Condition cache insert, query id: "
2891
12.9k
                               << print_id(_opts.runtime_state->query_id())
2892
12.9k
                               << ", rowset id: " << _opts.rowset_id.to_string()
2893
12.9k
                               << ", segment id: " << _segment->id()
2894
12.9k
                               << ", cache digest: " << _opts.condition_cache_digest;
2895
12.9k
                    condition_cache->insert(cache_key, std::move(_condition_cache));
2896
12.9k
                }
2897
12.9k
                return res;
2898
12.9k
            }
2899
2900
12.9k
            RETURN_IF_ERROR(res);
2901
            // reverse block row order if read_orderby_key_reverse is true for key topn
2902
            // it should be processed for all success _next_batch_internal
2903
12.9k
            if (_opts.read_orderby_key_reverse) {
2904
12.9k
                size_t num_rows = block->rows();
2905
12.9k
                if (num_rows == 0) {
2906
12.9k
                    return Status::OK();
2907
12.9k
                }
2908
12.9k
                size_t num_columns = block->columns();
2909
12.9k
                IColumn::Permutation permutation;
2910
12.9k
                for (size_t i = 0; i < num_rows; ++i) permutation.emplace_back(num_rows - 1 - i);
2911
2912
12.9k
                for (size_t i = 0; i < num_columns; ++i)
2913
12.9k
                    block->get_by_position(i).column =
2914
12.9k
                            block->get_by_position(i).column->permute(permutation, num_rows);
2915
12.9k
            }
2916
2917
12.9k
            RETURN_IF_ERROR(block->check_type_and_column());
2918
2919
            // Adaptive batch size: update EWMA estimate from the completed batch.
2920
            // block->bytes() is accurate here: predicates have been applied and non-predicate
2921
            // columns have been filled for surviving rows by _next_batch_internal.
2922
12.9k
            if (_block_size_predictor && block->rows() > 0) {
2923
12.9k
                _block_size_predictor->update(*block);
2924
12.9k
            }
2925
2926
12.9k
            return Status::OK();
2927
12.9k
        });
2928
12.9k
    }();
2929
2930
    // if rows read by batch is 0, will return end of file, we should not remove segment cache in this situation.
2931
12.9k
    if (!status.ok() && !status.is<END_OF_FILE>()) {
2932
0
        _segment->update_healthy_status(status);
2933
0
    }
2934
12.9k
    return status;
2935
12.9k
}
2936
2937
12.9k
Status SegmentIterator::_convert_to_expected_type(const std::vector<ColumnId>& col_ids) {
2938
26.3k
    for (ColumnId i : col_ids) {
2939
26.3k
        if (!_current_return_columns[i] || _converted_column_ids[i] || _is_pred_column[i]) {
2940
467
            continue;
2941
467
        }
2942
25.9k
        const TabletColumn* column_desc = _schema->column(i);
2943
25.9k
        DataTypePtr expected_type = Schema::get_data_type_ptr(*column_desc);
2944
25.9k
        DataTypePtr file_column_type = _storage_name_and_type[i].second;
2945
25.9k
        if (!file_column_type->equals(*expected_type)) {
2946
0
            ColumnPtr expected;
2947
0
            ColumnPtr original = _current_return_columns[i]->assert_mutable()->get_ptr();
2948
0
            RETURN_IF_ERROR(variant_util::cast_column({original, file_column_type, ""},
2949
0
                                                      expected_type, &expected));
2950
0
            _current_return_columns[i] = expected->assert_mutable();
2951
0
            _converted_column_ids[i] = true;
2952
0
            VLOG_DEBUG << fmt::format("Convert {} fom file column type {} to {}, num_rows {}",
2953
0
                                      column_desc->path_info_ptr() == nullptr
2954
0
                                              ? ""
2955
0
                                              : column_desc->path_info_ptr()->get_path(),
2956
0
                                      file_column_type->get_name(), expected_type->get_name(),
2957
0
                                      _current_return_columns[i]->size());
2958
0
        }
2959
25.9k
    }
2960
12.9k
    return Status::OK();
2961
12.9k
}
2962
2963
Status SegmentIterator::copy_column_data_by_selector(IColumn* input_col_ptr,
2964
                                                     MutableColumnPtr& output_col,
2965
                                                     uint16_t* sel_rowid_idx, uint16_t select_size,
2966
1.39k
                                                     size_t batch_size) {
2967
1.39k
    if (output_col->is_nullable() != input_col_ptr->is_nullable()) {
2968
0
        LOG(WARNING) << "nullable mismatch for output_column: " << output_col->dump_structure()
2969
0
                     << " input_column: " << input_col_ptr->dump_structure()
2970
0
                     << " select_size: " << select_size;
2971
0
        return Status::RuntimeError("copy_column_data_by_selector nullable mismatch");
2972
0
    }
2973
1.39k
    output_col->reserve(select_size);
2974
1.39k
    return input_col_ptr->filter_by_selector(sel_rowid_idx, select_size, output_col.get());
2975
1.39k
}
2976
2977
12.9k
Status SegmentIterator::_next_batch_internal(Block* block) {
2978
12.9k
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().segment_iterator_next_batch);
2979
2980
12.9k
    bool is_mem_reuse = block->mem_reuse();
2981
12.9k
    DCHECK(is_mem_reuse);
2982
2983
12.9k
    RETURN_IF_ERROR(_lazy_init(block));
2984
2985
12.9k
    SCOPED_RAW_TIMER(&_opts.stats->block_load_ns);
2986
2987
12.9k
    if (_opts.read_limit > 0 && _rows_returned >= _opts.read_limit) {
2988
0
        return _process_eof(block);
2989
0
    }
2990
2991
    // If the row bitmap size is smaller than nrows_read_limit, there's no need to reserve that many column rows.
2992
12.9k
    uint32_t nrows_read_limit =
2993
12.9k
            std::min(cast_set<uint32_t>(_row_bitmap.cardinality()), _opts.block_row_max);
2994
12.9k
    if (_can_opt_limit_reads()) {
2995
        // No SegmentIterator-side conjunct remains to be evaluated, so LIMIT is equivalent before
2996
        // and after filtering. Cap the first read directly; this is the no-conjunct fast path that
2997
        // avoids reading rows past the pushed-down local LIMIT.
2998
0
        size_t cap = (_opts.read_limit > _rows_returned) ? (_opts.read_limit - _rows_returned) : 0;
2999
0
        if (cap < nrows_read_limit) {
3000
0
            nrows_read_limit = static_cast<uint32_t>(cap);
3001
0
        }
3002
0
    }
3003
12.9k
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_1", {
3004
12.9k
        if (nrows_read_limit != 1) {
3005
12.9k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
3006
12.9k
                    "topn opt 1 execute failed: nrows_read_limit={}, "
3007
12.9k
                    "_opts.read_limit={}",
3008
12.9k
                    nrows_read_limit, _opts.read_limit);
3009
12.9k
        }
3010
12.9k
    })
3011
3012
12.9k
    RETURN_IF_ERROR(_init_current_block(block, _current_return_columns, nrows_read_limit));
3013
12.9k
    _converted_column_ids.assign(_schema->columns().size(), false);
3014
3015
12.9k
    _selected_size = 0;
3016
12.9k
    RETURN_IF_ERROR(_read_columns_by_index(nrows_read_limit, _selected_size));
3017
12.9k
    _replace_version_col_if_needed(_predicate_column_ids, _selected_size);
3018
12.9k
    _update_lsn_col_if_needed(_predicate_column_ids, _selected_size);
3019
12.9k
    _update_tso_col_if_needed(_predicate_column_ids, _selected_size);
3020
3021
12.9k
    _opts.stats->blocks_load += 1;
3022
12.9k
    _opts.stats->raw_rows_read += _selected_size;
3023
3024
12.9k
    if (_selected_size == 0) {
3025
2.81k
        return _process_eof(block);
3026
2.81k
    }
3027
3028
10.1k
    if (_is_need_vec_eval || _is_need_short_eval || _is_need_expr_eval) {
3029
1.69k
        _sel_rowid_idx.resize(_selected_size);
3030
3031
1.69k
        if (_is_need_vec_eval || _is_need_short_eval) {
3032
1.69k
            _convert_dict_code_for_predicate_if_necessary();
3033
3034
            // step 1: evaluate vectorization predicate
3035
1.69k
            _selected_size =
3036
1.69k
                    _evaluate_vectorization_predicate(_sel_rowid_idx.data(), _selected_size);
3037
3038
            // step 2: evaluate short circuit predicate
3039
            // todo(wb) research whether need to read short predicate after vectorization evaluation
3040
            //          to reduce cost of read short circuit columns.
3041
            //          In SSB test, it make no difference; So need more scenarios to test
3042
1.69k
            _selected_size =
3043
1.69k
                    _evaluate_short_circuit_predicate(_sel_rowid_idx.data(), _selected_size);
3044
1.69k
            VLOG_DEBUG << fmt::format("After evaluate predicates, selected size: {} ",
3045
0
                                      _selected_size);
3046
1.69k
            if (_selected_size > 0) {
3047
                // step 3.1: output short circuit and predicate column
3048
                // when lazy materialization enables, _predicate_column_ids = distinct(_short_cir_pred_column_ids + _vec_pred_column_ids)
3049
                // see _vec_init_lazy_materialization
3050
                // todo(wb) need to tell input columnids from output columnids
3051
1.66k
                RETURN_IF_ERROR(_output_column_by_sel_idx(block, _predicate_column_ids,
3052
1.66k
                                                          _sel_rowid_idx.data(), _selected_size));
3053
3054
                // step 3.2: read remaining expr column and evaluate it.
3055
1.66k
                if (_is_need_expr_eval) {
3056
                    // The predicate column contains the remaining expr column, no need second read.
3057
0
                    if (_common_expr_column_ids.size() > 0) {
3058
0
                        SCOPED_RAW_TIMER(&_opts.stats->non_predicate_read_ns);
3059
0
                        RETURN_IF_ERROR(_read_columns_by_rowids(
3060
0
                                _common_expr_column_ids, _block_rowids, _sel_rowid_idx.data(),
3061
0
                                _selected_size, &_current_return_columns));
3062
0
                        _replace_version_col_if_needed(_common_expr_column_ids, _selected_size);
3063
0
                        _update_lsn_col_if_needed(_common_expr_column_ids, _selected_size);
3064
0
                        _update_tso_col_if_needed(_common_expr_column_ids, _selected_size);
3065
0
                        RETURN_IF_ERROR(_process_columns(_common_expr_column_ids, block));
3066
0
                    }
3067
3068
0
                    DCHECK(block->columns() > _schema_block_id_map[*_common_expr_columns.begin()]);
3069
0
                    RETURN_IF_ERROR(
3070
0
                            _process_common_expr(_sel_rowid_idx.data(), _selected_size, block));
3071
0
                }
3072
1.66k
            } else {
3073
30
                _fill_column_nothing();
3074
30
                if (_is_need_expr_eval) {
3075
0
                    RETURN_IF_ERROR(_process_columns(_common_expr_column_ids, block));
3076
0
                }
3077
30
            }
3078
1.69k
        } else if (_is_need_expr_eval) {
3079
0
            DCHECK(!_predicate_column_ids.empty());
3080
0
            RETURN_IF_ERROR(_process_columns(_predicate_column_ids, block));
3081
            // first read all rows are insert block, initialize sel_rowid_idx to all rows.
3082
0
            for (uint16_t i = 0; i < _selected_size; ++i) {
3083
0
                _sel_rowid_idx[i] = i;
3084
0
            }
3085
0
            RETURN_IF_ERROR(_process_common_expr(_sel_rowid_idx.data(), _selected_size, block));
3086
0
        }
3087
3088
1.69k
        RETURN_IF_ERROR(_apply_read_limit_to_selected_rows(block, _selected_size));
3089
3090
        // step4: read non_predicate column
3091
1.69k
        if (_selected_size > 0) {
3092
1.66k
            if (!_non_predicate_columns.empty()) {
3093
1.38k
                RETURN_IF_ERROR(_read_columns_by_rowids(
3094
1.38k
                        _non_predicate_columns, _block_rowids, _sel_rowid_idx.data(),
3095
1.38k
                        _selected_size, &_current_return_columns,
3096
1.38k
                        _opts.condition_cache_digest && !_find_condition_cache));
3097
1.38k
                _replace_version_col_if_needed(_non_predicate_columns, _selected_size);
3098
1.38k
                _update_lsn_col_if_needed(_non_predicate_columns, _selected_size);
3099
1.38k
                _update_tso_col_if_needed(_non_predicate_columns, _selected_size);
3100
1.38k
            } else {
3101
286
                if (_opts.condition_cache_digest && !_find_condition_cache) {
3102
0
                    auto& condition_cache = *_condition_cache;
3103
0
                    for (size_t i = 0; i < _selected_size; ++i) {
3104
0
                        auto rowid = _block_rowids[_sel_rowid_idx[i]];
3105
0
                        condition_cache[rowid / SegmentIterator::CONDITION_CACHE_OFFSET] = true;
3106
0
                    }
3107
0
                }
3108
286
            }
3109
1.66k
        }
3110
1.69k
    }
3111
3112
    // step5: output columns
3113
10.1k
    RETURN_IF_ERROR(_output_non_pred_columns(block));
3114
    // Convert inverted index bitmaps to result columns for virtual column exprs
3115
    // (e.g., MATCH projections). This must run before _materialization_of_virtual_column
3116
    // so that fast_execute() can find the pre-computed result columns.
3117
10.1k
    if (!_virtual_column_exprs.empty()) {
3118
0
        bool use_sel = _is_need_vec_eval || _is_need_short_eval || _is_need_expr_eval;
3119
0
        uint16_t* sel_rowid_idx = use_sel ? _sel_rowid_idx.data() : nullptr;
3120
0
        std::vector<VExprContext*> vir_ctxs;
3121
0
        vir_ctxs.reserve(_virtual_column_exprs.size());
3122
0
        for (auto& [cid, ctx] : _virtual_column_exprs) {
3123
0
            vir_ctxs.push_back(ctx.get());
3124
0
        }
3125
0
        _output_index_result_column(vir_ctxs, sel_rowid_idx, _selected_size, block);
3126
0
    }
3127
10.1k
    RETURN_IF_ERROR(_materialization_of_virtual_column(block));
3128
    // shrink char_type suffix zero data
3129
10.1k
    block->shrink_char_type_column_suffix_zero(_char_type_idx);
3130
10.1k
    if (_opts.read_limit > 0) {
3131
0
        _rows_returned += block->rows();
3132
0
    }
3133
10.1k
    return _check_output_block(block);
3134
10.1k
}
3135
3136
0
Status SegmentIterator::_process_columns(const std::vector<ColumnId>& column_ids, Block* block) {
3137
0
    RETURN_IF_ERROR(_convert_to_expected_type(column_ids));
3138
0
    for (auto cid : column_ids) {
3139
0
        auto loc = _schema_block_id_map[cid];
3140
0
        block->replace_by_position(loc, std::move(_current_return_columns[cid]));
3141
0
    }
3142
0
    return Status::OK();
3143
0
}
3144
3145
30
void SegmentIterator::_fill_column_nothing() {
3146
    // If column_predicate filters out all rows, the corresponding column in _current_return_columns[cid] must be a ColumnNothing.
3147
    // Because:
3148
    // 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.
3149
    // 2. When select_size == 0, the read method of VirtualColumnIterator will definitely not be called, so the corresponding Column remains a ColumnNothing
3150
30
    for (const auto pair : _vir_cid_to_idx_in_block) {
3151
0
        auto cid = pair.first;
3152
0
        auto pos = pair.second;
3153
0
        [[maybe_unused]] const auto* nothing_col =
3154
0
                assert_cast<const ColumnNothing*>(_current_return_columns[cid].get());
3155
0
        _current_return_columns[cid] = _opts.vir_col_idx_to_type[pos]->create_column();
3156
0
    }
3157
30
}
3158
3159
10.1k
Status SegmentIterator::_check_output_block(Block* block) {
3160
10.1k
#ifndef NDEBUG
3161
10.1k
    size_t rows = block->rows();
3162
10.1k
    size_t idx = 0;
3163
20.7k
    for (const auto& entry : *block) {
3164
20.7k
        if (!entry.column) {
3165
0
            return Status::InternalError(
3166
0
                    "Column in idx {} is null, block columns {}, normal_columns {}, "
3167
0
                    "virtual_columns {}",
3168
0
                    idx, block->columns(), _schema->num_column_ids(), _virtual_column_exprs.size());
3169
20.7k
        } else if (check_and_get_column<ColumnNothing>(entry.column.get())) {
3170
0
            if (rows > 0) {
3171
0
                std::vector<std::string> vcid_to_idx;
3172
0
                for (const auto& pair : _vir_cid_to_idx_in_block) {
3173
0
                    vcid_to_idx.push_back(fmt::format("{}-{}", pair.first, pair.second));
3174
0
                }
3175
0
                std::string vir_cid_to_idx_in_block_msg =
3176
0
                        fmt::format("_vir_cid_to_idx_in_block:[{}]", fmt::join(vcid_to_idx, ","));
3177
0
                return Status::InternalError(
3178
0
                        "Column in idx {} is nothing, block columns {}, normal_columns {}, "
3179
0
                        "vir_cid_to_idx_in_block_msg {}",
3180
0
                        idx, block->columns(), _schema->num_column_ids(),
3181
0
                        vir_cid_to_idx_in_block_msg);
3182
0
            }
3183
20.7k
        } else if (entry.column->size() != rows) {
3184
0
            return Status::InternalError(
3185
0
                    "Unmatched size {}, expected {}, column: {}, type: {}, idx_in_block: {}, "
3186
0
                    "block: {}",
3187
0
                    entry.column->size(), rows, entry.column->get_name(), entry.type->get_name(),
3188
0
                    idx, block->dump_structure());
3189
0
        }
3190
20.7k
        idx++;
3191
20.7k
    }
3192
10.1k
#endif
3193
10.1k
    return Status::OK();
3194
10.1k
}
3195
3196
0
Status SegmentIterator::_process_column_predicate() {
3197
0
    return Status::OK();
3198
0
}
3199
3200
2.81k
Status SegmentIterator::_process_eof(Block* block) {
3201
    // Convert all columns in _current_return_columns to schema column
3202
2.81k
    RETURN_IF_ERROR(_convert_to_expected_type(_schema->column_ids()));
3203
9.66k
    for (int i = 0; i < block->columns(); i++) {
3204
6.84k
        auto cid = _schema->column_id(i);
3205
6.84k
        if (!_is_pred_column[cid]) {
3206
6.56k
            block->replace_by_position(i, std::move(_current_return_columns[cid]));
3207
6.56k
        }
3208
6.84k
    }
3209
2.81k
    block->clear_column_data();
3210
    // clear and release iterators memory footprint in advance
3211
2.81k
    _column_iterators.clear();
3212
2.81k
    _index_iterators.clear();
3213
2.81k
    return Status::EndOfFile("no more data in segment");
3214
2.81k
}
3215
3216
Status SegmentIterator::_process_common_expr(uint16_t* sel_rowid_idx, uint16_t& selected_size,
3217
0
                                             Block* block) {
3218
    // Here we just use col0 as row_number indicator. when reach here, we will calculate the predicates first.
3219
    //  then use the result to reduce our data read(that is, expr push down). there's now row in block means the first
3220
    //  column is not in common expr. so it's safe to replace it temporarily to provide correct `selected_size`.
3221
0
    VLOG_DEBUG << fmt::format("Execute common expr. block rows {}, selected size {}", block->rows(),
3222
0
                              _selected_size);
3223
3224
0
    bool need_mock_col = block->rows() != selected_size;
3225
0
    MutableColumnPtr col0;
3226
0
    if (need_mock_col) {
3227
0
        col0 = std::move(*block->get_by_position(0).column).mutate();
3228
0
        block->replace_by_position(
3229
0
                0, block->get_by_position(0).type->create_column_const_with_default_value(
3230
0
                           _selected_size));
3231
0
    }
3232
3233
0
    std::vector<VExprContext*> common_ctxs;
3234
0
    common_ctxs.reserve(_common_expr_ctxs_push_down.size());
3235
0
    for (auto& ctx : _common_expr_ctxs_push_down) {
3236
0
        common_ctxs.push_back(ctx.get());
3237
0
    }
3238
0
    _output_index_result_column(common_ctxs, _sel_rowid_idx.data(), _selected_size, block);
3239
0
    block->shrink_char_type_column_suffix_zero(_char_type_idx);
3240
0
    RETURN_IF_ERROR(_execute_common_expr(_sel_rowid_idx.data(), _selected_size, block));
3241
3242
0
    if (need_mock_col) {
3243
0
        block->replace_by_position(0, std::move(col0));
3244
0
    }
3245
3246
0
    VLOG_DEBUG << fmt::format("Execute common expr end. block rows {}, selected size {}",
3247
0
                              block->rows(), _selected_size);
3248
0
    return Status::OK();
3249
0
}
3250
3251
Status SegmentIterator::_execute_common_expr(uint16_t* sel_rowid_idx, uint16_t& selected_size,
3252
0
                                             Block* block) {
3253
0
    SCOPED_RAW_TIMER(&_opts.stats->expr_filter_ns);
3254
0
    DCHECK(!_common_expr_ctxs_push_down.empty());
3255
0
    DCHECK(block->rows() != 0);
3256
0
    int prev_columns = block->columns();
3257
0
    uint16_t original_size = selected_size;
3258
0
    _opts.stats->expr_cond_input_rows += original_size;
3259
3260
0
    IColumn::Filter filter;
3261
0
    RETURN_IF_ERROR(VExprContext::execute_conjuncts_and_filter_block(
3262
0
            _common_expr_ctxs_push_down, block, _columns_to_filter, prev_columns, filter));
3263
3264
0
    selected_size = _evaluate_common_expr_filter(sel_rowid_idx, selected_size, filter);
3265
0
    _opts.stats->rows_expr_cond_filtered += original_size - selected_size;
3266
0
    return Status::OK();
3267
0
}
3268
3269
uint16_t SegmentIterator::_evaluate_common_expr_filter(uint16_t* sel_rowid_idx,
3270
                                                       uint16_t selected_size,
3271
0
                                                       const IColumn::Filter& filter) {
3272
0
    size_t count = filter.size() - simd::count_zero_num((int8_t*)filter.data(), filter.size());
3273
0
    if (count == 0) {
3274
0
        return 0;
3275
0
    } else {
3276
0
        const UInt8* filt_pos = filter.data();
3277
3278
0
        uint16_t new_size = 0;
3279
0
        uint32_t sel_pos = 0;
3280
0
        const uint32_t sel_end = selected_size;
3281
0
        static constexpr size_t SIMD_BYTES = simd::bits_mask_length();
3282
0
        const uint32_t sel_end_simd = sel_pos + selected_size / SIMD_BYTES * SIMD_BYTES;
3283
3284
0
        while (sel_pos < sel_end_simd) {
3285
0
            auto mask = simd::bytes_mask_to_bits_mask(filt_pos + sel_pos);
3286
0
            if (0 == mask) {
3287
                //pass
3288
0
            } else if (simd::bits_mask_all() == mask) {
3289
0
                for (uint32_t i = 0; i < SIMD_BYTES; i++) {
3290
0
                    sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos + i];
3291
0
                }
3292
0
            } else {
3293
0
                simd::iterate_through_bits_mask(
3294
0
                        [&](const size_t bit_pos) {
3295
0
                            sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos + bit_pos];
3296
0
                        },
3297
0
                        mask);
3298
0
            }
3299
0
            sel_pos += SIMD_BYTES;
3300
0
        }
3301
3302
0
        for (; sel_pos < sel_end; sel_pos++) {
3303
0
            if (filt_pos[sel_pos]) {
3304
0
                sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos];
3305
0
            }
3306
0
        }
3307
0
        return new_size;
3308
0
    }
3309
0
}
3310
3311
void SegmentIterator::_output_index_result_column(const std::vector<VExprContext*>& expr_ctxs,
3312
                                                  uint16_t* sel_rowid_idx, uint16_t select_size,
3313
0
                                                  Block* block) {
3314
0
    SCOPED_RAW_TIMER(&_opts.stats->output_index_result_column_timer);
3315
0
    if (block->rows() == 0) {
3316
0
        return;
3317
0
    }
3318
0
    for (auto* expr_ctx_ptr : expr_ctxs) {
3319
0
        auto index_ctx = expr_ctx_ptr->get_index_context();
3320
0
        if (index_ctx == nullptr) {
3321
0
            continue;
3322
0
        }
3323
0
        for (auto& inverted_index_result_bitmap_for_expr : index_ctx->get_index_result_bitmap()) {
3324
0
            const auto* expr = inverted_index_result_bitmap_for_expr.first;
3325
0
            const auto& result_bitmap = inverted_index_result_bitmap_for_expr.second;
3326
0
            const auto& index_result_bitmap = result_bitmap.get_data_bitmap();
3327
0
            auto index_result_column = ColumnUInt8::create();
3328
0
            ColumnUInt8::Container& vec_match_pred = index_result_column->get_data();
3329
0
            vec_match_pred.resize(block->rows());
3330
0
            std::fill(vec_match_pred.begin(), vec_match_pred.end(), 0);
3331
3332
0
            const auto& null_bitmap = result_bitmap.get_null_bitmap();
3333
0
            bool has_null_bitmap = null_bitmap != nullptr && !null_bitmap->isEmpty();
3334
0
            bool expr_returns_nullable = expr->data_type()->is_nullable();
3335
3336
0
            ColumnUInt8::MutablePtr null_map_column = nullptr;
3337
0
            ColumnUInt8::Container* null_map_data = nullptr;
3338
0
            if (has_null_bitmap && expr_returns_nullable) {
3339
0
                null_map_column = ColumnUInt8::create();
3340
0
                auto& null_map_vec = null_map_column->get_data();
3341
0
                null_map_vec.resize(block->rows());
3342
0
                std::fill(null_map_vec.begin(), null_map_vec.end(), 0);
3343
0
                null_map_data = &null_map_column->get_data();
3344
0
            }
3345
3346
0
            roaring::BulkContext bulk_context;
3347
0
            for (uint32_t i = 0; i < select_size; i++) {
3348
0
                auto rowid = sel_rowid_idx ? _block_rowids[sel_rowid_idx[i]] : _block_rowids[i];
3349
0
                if (index_result_bitmap) {
3350
0
                    vec_match_pred[i] = index_result_bitmap->containsBulk(bulk_context, rowid);
3351
0
                }
3352
0
                if (null_map_data != nullptr && null_bitmap->contains(rowid)) {
3353
0
                    (*null_map_data)[i] = 1;
3354
0
                    vec_match_pred[i] = 0;
3355
0
                }
3356
0
            }
3357
3358
0
            DCHECK(block->rows() == vec_match_pred.size());
3359
3360
0
            if (null_map_column) {
3361
0
                index_ctx->set_index_result_column_for_expr(
3362
0
                        expr, ColumnNullable::create(std::move(index_result_column),
3363
0
                                                     std::move(null_map_column)));
3364
0
            } else {
3365
0
                index_ctx->set_index_result_column_for_expr(expr, std::move(index_result_column));
3366
0
            }
3367
0
        }
3368
0
    }
3369
0
}
3370
3371
1.69k
void SegmentIterator::_convert_dict_code_for_predicate_if_necessary() {
3372
1.69k
    for (auto predicate : _short_cir_eval_predicate) {
3373
0
        _convert_dict_code_for_predicate_if_necessary_impl(predicate);
3374
0
    }
3375
3376
1.69k
    for (auto predicate : _pre_eval_block_predicate) {
3377
0
        _convert_dict_code_for_predicate_if_necessary_impl(predicate);
3378
0
    }
3379
3380
1.69k
    for (auto column_id : _delete_range_column_ids) {
3381
1.55k
        _current_return_columns[column_id].get()->convert_dict_codes_if_necessary();
3382
1.55k
    }
3383
3384
1.69k
    for (auto column_id : _delete_bloom_filter_column_ids) {
3385
0
        _current_return_columns[column_id].get()->initialize_hash_values_for_runtime_filter();
3386
0
    }
3387
1.69k
}
3388
3389
void SegmentIterator::_convert_dict_code_for_predicate_if_necessary_impl(
3390
0
        std::shared_ptr<ColumnPredicate> predicate) {
3391
0
    auto& column = _current_return_columns[predicate->column_id()];
3392
0
    auto* col_ptr = column.get();
3393
3394
0
    if (PredicateTypeTraits::is_range(predicate->type())) {
3395
0
        col_ptr->convert_dict_codes_if_necessary();
3396
0
    } else if (PredicateTypeTraits::is_bloom_filter(predicate->type())) {
3397
0
        col_ptr->initialize_hash_values_for_runtime_filter();
3398
0
    }
3399
0
}
3400
3401
2.93k
Status SegmentIterator::current_block_row_locations(std::vector<RowLocation>* block_row_locations) {
3402
2.93k
    DCHECK(_opts.record_rowids);
3403
2.93k
    DCHECK_GE(_block_rowids.size(), _selected_size);
3404
2.93k
    block_row_locations->resize(_selected_size);
3405
2.93k
    uint32_t sid = segment_id();
3406
2.93k
    if (!_is_need_vec_eval && !_is_need_short_eval && !_is_need_expr_eval) {
3407
4.24M
        for (auto i = 0; i < _selected_size; i++) {
3408
4.23M
            (*block_row_locations)[i] = RowLocation(sid, _block_rowids[i]);
3409
4.23M
        }
3410
1.76k
    } else {
3411
2.46M
        for (auto i = 0; i < _selected_size; i++) {
3412
2.46M
            (*block_row_locations)[i] = RowLocation(sid, _block_rowids[_sel_rowid_idx[i]]);
3413
2.46M
        }
3414
1.16k
    }
3415
2.93k
    return Status::OK();
3416
2.93k
}
3417
3418
2.82k
Status SegmentIterator::_construct_compound_expr_context() {
3419
2.82k
    ColumnIteratorOptions iter_opts {
3420
2.82k
            .use_page_cache = _opts.use_page_cache,
3421
2.82k
            .file_reader = _file_reader.get(),
3422
2.82k
            .stats = _opts.stats,
3423
2.82k
            .io_ctx = _opts.io_ctx,
3424
2.82k
    };
3425
2.82k
    auto inverted_index_context = std::make_shared<IndexExecContext>(
3426
2.82k
            _schema->column_ids(), _index_iterators, _storage_name_and_type,
3427
2.82k
            _common_expr_index_exec_status, _score_runtime, _segment.get(), iter_opts);
3428
2.82k
    inverted_index_context->set_index_query_context(_index_query_context);
3429
2.82k
    for (const auto& expr_ctx : _opts.common_expr_ctxs_push_down) {
3430
0
        VExprContextSPtr context;
3431
        // _ann_range_search_runtime will do deep copy.
3432
0
        RETURN_IF_ERROR(expr_ctx->clone(_opts.runtime_state, context));
3433
0
        context->set_index_context(inverted_index_context);
3434
0
        _common_expr_ctxs_push_down.emplace_back(context);
3435
0
    }
3436
    // Clone virtual column exprs before setting IndexExecContext, because
3437
    // IndexExecContext holds segment-specific index iterator references.
3438
    // Without cloning, shared VExprContext would be overwritten per-segment
3439
    // and could point to the wrong segment's context.
3440
2.82k
    for (auto& [cid, expr_ctx] : _virtual_column_exprs) {
3441
0
        VExprContextSPtr context;
3442
0
        RETURN_IF_ERROR(expr_ctx->clone(_opts.runtime_state, context));
3443
0
        context->set_index_context(inverted_index_context);
3444
0
        expr_ctx = context;
3445
0
    }
3446
2.82k
    RETURN_IF_ERROR(rebind_storage_exprs_to_reader_schema(
3447
2.82k
            _opts, *_schema, _common_expr_ctxs_push_down, _virtual_column_exprs));
3448
2.82k
    return Status::OK();
3449
2.82k
}
3450
3451
2.82k
void SegmentIterator::_calculate_common_expr_index_exec_status() {
3452
2.82k
    for (const auto& root_expr_ctx : _common_expr_ctxs_push_down) {
3453
0
        const auto& root_expr = root_expr_ctx->root();
3454
0
        if (root_expr == nullptr) {
3455
0
            continue;
3456
0
        }
3457
0
        _common_expr_to_slotref_map[root_expr_ctx.get()] = std::unordered_map<ColumnId, VExpr*>();
3458
3459
0
        std::stack<VExprSPtr> stack;
3460
0
        stack.emplace(root_expr);
3461
3462
0
        while (!stack.empty()) {
3463
0
            const auto& expr = stack.top();
3464
0
            stack.pop();
3465
3466
0
            for (const auto& child : expr->children()) {
3467
0
                if (child->is_virtual_slot_ref()) {
3468
                    // Expand virtual slot ref to its underlying expression tree and
3469
                    // collect real slot refs used inside. We still associate those
3470
                    // slot refs with the current parent expr node for inverted index
3471
                    // tracking, just like normal slot refs.
3472
0
                    auto* vir_slot_ref = assert_cast<VirtualSlotRef*>(child.get());
3473
0
                    auto vir_expr = vir_slot_ref->get_virtual_column_expr();
3474
0
                    if (vir_expr) {
3475
0
                        std::stack<VExprSPtr> vir_stack;
3476
0
                        vir_stack.emplace(vir_expr);
3477
3478
0
                        while (!vir_stack.empty()) {
3479
0
                            const auto& vir_node = vir_stack.top();
3480
0
                            vir_stack.pop();
3481
3482
0
                            for (const auto& vir_child : vir_node->children()) {
3483
0
                                if (vir_child->is_slot_ref()) {
3484
0
                                    auto* inner_slot_ref = assert_cast<VSlotRef*>(vir_child.get());
3485
0
                                    _common_expr_index_exec_status[_schema->column_id(
3486
0
                                            inner_slot_ref->column_id())][expr.get()] = false;
3487
0
                                    _common_expr_to_slotref_map[root_expr_ctx.get()]
3488
0
                                                               [inner_slot_ref->column_id()] =
3489
0
                                                                       expr.get();
3490
0
                                }
3491
3492
0
                                if (!vir_child->children().empty()) {
3493
0
                                    vir_stack.emplace(vir_child);
3494
0
                                }
3495
0
                            }
3496
0
                        }
3497
0
                    }
3498
0
                }
3499
                // Example: CAST(v['a'] AS VARCHAR) MATCH 'hello', do not add CAST expr to index tracking.
3500
0
                auto expr_without_cast = VExpr::expr_without_cast(child);
3501
0
                if (expr_without_cast->is_slot_ref() && expr->op() != TExprOpcode::CAST) {
3502
0
                    auto* column_slot_ref = assert_cast<VSlotRef*>(expr_without_cast.get());
3503
0
                    _common_expr_index_exec_status[_schema->column_id(column_slot_ref->column_id())]
3504
0
                                                  [expr.get()] = false;
3505
0
                    _common_expr_to_slotref_map[root_expr_ctx.get()][column_slot_ref->column_id()] =
3506
0
                            expr.get();
3507
0
                }
3508
0
            }
3509
3510
0
            const auto& children = expr->children();
3511
0
            for (int i = cast_set<int>(children.size()) - 1; i >= 0; --i) {
3512
0
                if (!children[i]->children().empty()) {
3513
0
                    stack.emplace(children[i]);
3514
0
                }
3515
0
            }
3516
0
        }
3517
0
    }
3518
2.82k
}
3519
3520
bool SegmentIterator::_no_need_read_key_data(ColumnId cid, MutableColumnPtr& column,
3521
27.1k
                                             size_t nrows_read) {
3522
27.1k
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_no_need_read_data_opt) {
3523
0
        return false;
3524
0
    }
3525
3526
27.1k
    if (!((_opts.tablet_schema->keys_type() == KeysType::DUP_KEYS ||
3527
27.1k
           (_opts.tablet_schema->keys_type() == KeysType::UNIQUE_KEYS &&
3528
11.1k
            _opts.enable_unique_key_merge_on_write)))) {
3529
7.58k
        return false;
3530
7.58k
    }
3531
3532
19.5k
    if (_opts.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
3533
19.5k
        return false;
3534
19.5k
    }
3535
3536
0
    if (!_opts.tablet_schema->column(cid).is_key()) {
3537
0
        return false;
3538
0
    }
3539
3540
0
    if (_has_delete_predicate(cid)) {
3541
0
        return false;
3542
0
    }
3543
3544
0
    if (!_check_all_conditions_passed_inverted_index_for_column(cid)) {
3545
0
        return false;
3546
0
    }
3547
3548
0
    if (column->is_nullable()) {
3549
0
        auto* nullable_col_ptr = reinterpret_cast<ColumnNullable*>(column.get());
3550
0
        nullable_col_ptr->get_null_map_column().insert_many_defaults(nrows_read);
3551
0
        nullable_col_ptr->get_nested_column_ptr()->insert_many_defaults(nrows_read);
3552
0
    } else {
3553
0
        column->insert_many_defaults(nrows_read);
3554
0
    }
3555
3556
0
    return true;
3557
0
}
3558
3559
19.5k
bool SegmentIterator::_has_delete_predicate(ColumnId cid) {
3560
19.5k
    std::set<uint32_t> delete_columns_set;
3561
19.5k
    _opts.delete_condition_predicates->get_all_column_ids(delete_columns_set);
3562
19.5k
    return delete_columns_set.contains(cid);
3563
19.5k
}
3564
3565
12.9k
bool SegmentIterator::_can_opt_limit_reads() {
3566
12.9k
    if (_opts.read_limit == 0) {
3567
12.9k
        return false;
3568
12.9k
    }
3569
3570
    // If SegmentIterator still needs to evaluate predicates/common exprs, LIMIT must be applied to
3571
    // post-filter rows by _apply_read_limit_to_selected_rows(); capping the raw read here could
3572
    // return fewer rows than the query LIMIT.
3573
7
    if (_is_need_vec_eval || _is_need_short_eval || _is_need_expr_eval) {
3574
3
        return false;
3575
3
    }
3576
3577
4
    if (_opts.delete_condition_predicates->num_of_column_predicate() > 0) {
3578
1
        return false;
3579
1
    }
3580
3581
3
    bool all_true = std::ranges::all_of(_schema->column_ids(), [this](auto cid) {
3582
3
        if (cid == _opts.tablet_schema->delete_sign_idx()) {
3583
0
            return true;
3584
0
        }
3585
3
        if (_check_all_conditions_passed_inverted_index_for_column(cid, true)) {
3586
2
            return true;
3587
2
        }
3588
1
        return false;
3589
3
    });
3590
3591
3
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_1", {
3592
3
        LOG(INFO) << "col_predicates: " << _col_predicates.size() << ", all_true: " << all_true;
3593
3
    })
3594
3595
3
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_2", {
3596
3
        if (all_true) {
3597
3
            return Status::Error<ErrorCode::INTERNAL_ERROR>("topn opt 2 execute failed");
3598
3
        }
3599
3
    })
3600
3601
3
    return all_true;
3602
3
}
3603
3604
// Before get next batch. make sure all virtual columns in block has type ColumnNothing.
3605
12.9k
void SegmentIterator::_init_virtual_columns(Block* block) {
3606
12.9k
    for (const auto& pair : _vir_cid_to_idx_in_block) {
3607
0
        auto& col_with_type_and_name = block->get_by_position(pair.second);
3608
0
        col_with_type_and_name.column = ColumnNothing::create(0);
3609
0
        col_with_type_and_name.type = _opts.vir_col_idx_to_type[pair.second];
3610
0
    }
3611
12.9k
}
3612
3613
10.1k
Status SegmentIterator::_materialization_of_virtual_column(Block* block) {
3614
    // Some expr can not process empty block, such as function `element_at`.
3615
    // So materialize virtual column in advance to avoid errors.
3616
10.1k
    if (block->rows() == 0) {
3617
30
        for (const auto& pair : _vir_cid_to_idx_in_block) {
3618
0
            auto& col_with_type_and_name = block->get_by_position(pair.second);
3619
0
            col_with_type_and_name.column = _opts.vir_col_idx_to_type[pair.second]->create_column();
3620
0
            col_with_type_and_name.type = _opts.vir_col_idx_to_type[pair.second];
3621
0
        }
3622
30
        return Status::OK();
3623
30
    }
3624
3625
10.0k
    for (const auto& cid_and_expr : _virtual_column_exprs) {
3626
0
        auto cid = cid_and_expr.first;
3627
0
        auto column_expr = cid_and_expr.second;
3628
0
        size_t idx_in_block = _vir_cid_to_idx_in_block[cid];
3629
0
        if (block->columns() <= idx_in_block) {
3630
0
            return Status::InternalError(
3631
0
                    "Virtual column index {} is out of range, block columns {}, "
3632
0
                    "virtual columns size {}, virtual column expr {}",
3633
0
                    idx_in_block, block->columns(), _vir_cid_to_idx_in_block.size(),
3634
0
                    column_expr->root()->debug_string());
3635
0
        } else if (block->get_by_position(idx_in_block).column.get() == nullptr) {
3636
0
            return Status::InternalError(
3637
0
                    "Virtual column index {} is null, block columns {}, virtual columns size {}, "
3638
0
                    "virtual column expr {}",
3639
0
                    idx_in_block, block->columns(), _vir_cid_to_idx_in_block.size(),
3640
0
                    column_expr->root()->debug_string());
3641
0
        }
3642
0
        block->shrink_char_type_column_suffix_zero(_char_type_idx);
3643
0
        if (check_and_get_column<const ColumnNothing>(
3644
0
                    block->get_by_position(idx_in_block).column.get())) {
3645
0
            VLOG_DEBUG << fmt::format("Virtual column is doing materialization, cid {}, col idx {}",
3646
0
                                      cid, idx_in_block);
3647
0
            ColumnPtr result_column;
3648
0
            RETURN_IF_ERROR(column_expr->execute(block, result_column));
3649
3650
0
            block->replace_by_position(idx_in_block, std::move(result_column));
3651
0
            if (block->get_by_position(idx_in_block).column->size() == 0) {
3652
0
                LOG_WARNING("Result of expr column {} is empty. cid {}, idx_in_block {}",
3653
0
                            column_expr->root()->debug_string(), cid, idx_in_block);
3654
0
            }
3655
0
        }
3656
0
    }
3657
10.0k
    return Status::OK();
3658
10.0k
}
3659
3660
2.82k
void SegmentIterator::_prepare_score_column_materialization() {
3661
2.82k
    if (_score_runtime == nullptr) {
3662
2.82k
        return;
3663
2.82k
    }
3664
3665
0
    ScoreRangeFilterPtr filter;
3666
0
    if (_score_runtime->has_score_range_filter()) {
3667
0
        const auto& range_info = _score_runtime->get_score_range_info();
3668
0
        filter = std::make_shared<ScoreRangeFilter>(range_info->op, range_info->threshold);
3669
0
    }
3670
3671
0
    IColumn::MutablePtr result_column;
3672
0
    auto result_row_ids = std::make_unique<std::vector<uint64_t>>();
3673
0
    if (_score_runtime->get_limit() > 0 && _col_predicates.empty() &&
3674
0
        _common_expr_ctxs_push_down.empty()) {
3675
0
        OrderType order_type = _score_runtime->is_asc() ? OrderType::ASC : OrderType::DESC;
3676
0
        _index_query_context->collection_similarity->get_topn_bm25_scores(
3677
0
                &_row_bitmap, result_column, result_row_ids, order_type,
3678
0
                _score_runtime->get_limit(), filter);
3679
0
    } else {
3680
0
        _index_query_context->collection_similarity->get_bm25_scores(&_row_bitmap, result_column,
3681
0
                                                                     result_row_ids, filter);
3682
0
    }
3683
0
    const size_t dst_col_idx = _score_runtime->get_dest_column_idx();
3684
0
    auto* column_iter = _column_iterators[_schema->column_id(dst_col_idx)].get();
3685
0
    auto* virtual_column_iter = dynamic_cast<VirtualColumnIterator*>(column_iter);
3686
0
    virtual_column_iter->prepare_materialization(
3687
0
            std::move(result_column),
3688
0
            std::shared_ptr<std::vector<uint64_t>>(std::move(result_row_ids)));
3689
0
}
3690
3691
} // namespace segment_v2
3692
} // namespace doris