Coverage Report

Created: 2026-05-15 16:10

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