Coverage Report

Created: 2026-07-07 22:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/column_reader.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/column_reader.h"
19
20
#include <assert.h>
21
#include <gen_cpp/Descriptors_types.h>
22
#include <gen_cpp/segment_v2.pb.h>
23
#include <glog/logging.h>
24
25
#include <algorithm>
26
#include <memory>
27
#include <ostream>
28
#include <set>
29
#include <string>
30
#include <utility>
31
32
#include "common/compiler_util.h" // IWYU pragma: keep
33
#include "common/status.h"
34
#include "core/assert_cast.h"
35
#include "core/binary_cast.hpp"
36
#include "core/column/column.h"
37
#include "core/column/column_array.h"
38
#include "core/column/column_map.h"
39
#include "core/column/column_nullable.h"
40
#include "core/column/column_struct.h"
41
#include "core/column/column_vector.h"
42
#include "core/data_type/data_type_agg_state.h"
43
#include "core/data_type/data_type_factory.hpp"
44
#include "core/data_type/data_type_nullable.h"
45
#include "core/data_type/define_primitive_type.h"
46
#include "core/decimal12.h"
47
#include "core/string_ref.h"
48
#include "core/types.h"
49
#include "core/value/decimalv2_value.h"
50
#include "core/value/vdatetime_value.h" //for VecDateTime
51
#include "io/fs/file_reader.h"
52
#include "storage/index/ann/ann_index_reader.h"
53
#include "storage/index/bloom_filter/bloom_filter.h"
54
#include "storage/index/bloom_filter/bloom_filter_index_reader.h"
55
#include "storage/index/index_file_reader.h"
56
#include "storage/index/index_reader.h"
57
#include "storage/index/inverted/analyzer/analyzer.h"
58
#include "storage/index/inverted/inverted_index_reader.h"
59
#include "storage/index/zone_map/zone_map_index.h"
60
#include "storage/iterators.h"
61
#include "storage/olap_common.h"
62
#include "storage/predicate/block_column_predicate.h"
63
#include "storage/predicate/column_predicate.h"
64
#include "storage/segment/binary_dict_page.h" // for BinaryDictPageDecoder
65
#include "storage/segment/binary_plain_page.h"
66
#include "storage/segment/column_meta_accessor.h"
67
#include "storage/segment/encoding_info.h" // for EncodingInfo
68
#include "storage/segment/page_decoder.h"
69
#include "storage/segment/page_handle.h" // for PageHandle
70
#include "storage/segment/page_io.h"
71
#include "storage/segment/page_pointer.h" // for PagePointer
72
#include "storage/segment/row_ranges.h"
73
#include "storage/segment/segment.h"
74
#include "storage/segment/segment_prefetcher.h"
75
#include "storage/segment/variant/variant_column_reader.h"
76
#include "storage/tablet/tablet_schema.h"
77
#include "storage/types.h" // for TypeInfo
78
#include "util/bitmap.h"
79
#include "util/block_compression.h"
80
#include "util/concurrency_stats.h"
81
#include "util/defer_op.h"
82
#include "util/rle_encoding.h" // for RleDecoder
83
#include "util/slice.h"
84
85
namespace doris::segment_v2 {
86
#include "storage/segment/column_reader.h"
87
88
0
inline bool read_as_string(PrimitiveType type) {
89
0
    return type == PrimitiveType::TYPE_STRING || type == PrimitiveType::INVALID_TYPE ||
90
0
           type == PrimitiveType::TYPE_BITMAP || type == PrimitiveType::TYPE_FIXED_LENGTH_OBJECT;
91
0
}
92
93
172
bool is_current_level_meta_access_path(const TColumnAccessPath& path) {
94
172
    if (path.data_access_path.path.size() != 1) {
95
91
        return false;
96
91
    }
97
81
    const auto& component = path.data_access_path.path[0];
98
81
    return StringCaseEqual()(component, ColumnIterator::ACCESS_OFFSET) ||
99
81
           StringCaseEqual()(component, ColumnIterator::ACCESS_NULL);
100
172
}
101
102
bool is_current_level_data_access_path(const TColumnAccessPath& path,
103
92
                                       const std::string& column_name) {
104
92
    return path.data_access_path.path.size() == 1 &&
105
92
           StringCaseEqual()(path.data_access_path.path[0], column_name);
106
92
}
107
108
99
void remove_current_level_meta_access_paths(TColumnAccessPaths& paths) {
109
99
    auto removed = std::ranges::remove_if(paths, is_current_level_meta_access_path);
110
99
    paths.erase(removed.begin(), removed.end());
111
99
}
112
113
Status ColumnReader::create_array(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
114
                                  const io::FileReaderSPtr& file_reader,
115
35
                                  std::shared_ptr<ColumnReader>* reader) {
116
35
    DCHECK(meta.children_columns_size() == 2 || meta.children_columns_size() == 3);
117
118
35
    std::shared_ptr<ColumnReader> item_reader;
119
35
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(0),
120
35
                                         meta.children_columns(0).num_rows(), file_reader,
121
35
                                         &item_reader));
122
123
35
    std::shared_ptr<ColumnReader> offset_reader;
124
35
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(1),
125
35
                                         meta.children_columns(1).num_rows(), file_reader,
126
35
                                         &offset_reader));
127
128
35
    std::shared_ptr<ColumnReader> null_reader;
129
35
    if (meta.is_nullable()) {
130
33
        RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(2),
131
33
                                             meta.children_columns(2).num_rows(), file_reader,
132
33
                                             &null_reader));
133
33
    }
134
135
    // The num rows of the array reader equals to the num rows of the length reader.
136
35
    uint64_t array_num_rows = meta.children_columns(1).num_rows();
137
35
    std::shared_ptr<ColumnReader> array_reader(
138
35
            new ColumnReader(opts, meta, array_num_rows, file_reader));
139
    //  array reader do not need to init
140
35
    array_reader->_sub_readers.resize(meta.children_columns_size());
141
35
    array_reader->_sub_readers[0] = std::move(item_reader);
142
35
    array_reader->_sub_readers[1] = std::move(offset_reader);
143
35
    if (meta.is_nullable()) {
144
33
        array_reader->_sub_readers[2] = std::move(null_reader);
145
33
    }
146
35
    array_reader->_meta_type = FieldType::OLAP_FIELD_TYPE_ARRAY;
147
35
    *reader = std::move(array_reader);
148
35
    return Status::OK();
149
35
}
150
151
Status ColumnReader::create_map(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
152
                                const io::FileReaderSPtr& file_reader,
153
796
                                std::shared_ptr<ColumnReader>* reader) {
154
    // map reader now has 3 sub readers for key, value, offsets(scalar), null(scala)
155
796
    DCHECK(meta.children_columns_size() == 3 || meta.children_columns_size() == 4);
156
796
    std::shared_ptr<ColumnReader> key_reader;
157
796
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(0),
158
796
                                         meta.children_columns(0).num_rows(), file_reader,
159
796
                                         &key_reader));
160
796
    std::shared_ptr<ColumnReader> val_reader;
161
796
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(1),
162
796
                                         meta.children_columns(1).num_rows(), file_reader,
163
796
                                         &val_reader));
164
796
    std::shared_ptr<ColumnReader> offset_reader;
165
796
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(2),
166
796
                                         meta.children_columns(2).num_rows(), file_reader,
167
796
                                         &offset_reader));
168
796
    std::shared_ptr<ColumnReader> null_reader;
169
796
    if (meta.is_nullable()) {
170
0
        RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(3),
171
0
                                             meta.children_columns(3).num_rows(), file_reader,
172
0
                                             &null_reader));
173
0
    }
174
175
    // The num rows of the map reader equals to the num rows of the length reader.
176
796
    uint64_t map_num_rows = meta.children_columns(2).num_rows();
177
796
    std::shared_ptr<ColumnReader> map_reader(
178
796
            new ColumnReader(opts, meta, map_num_rows, file_reader));
179
796
    map_reader->_sub_readers.resize(meta.children_columns_size());
180
181
796
    map_reader->_sub_readers[0] = std::move(key_reader);
182
796
    map_reader->_sub_readers[1] = std::move(val_reader);
183
796
    map_reader->_sub_readers[2] = std::move(offset_reader);
184
796
    if (meta.is_nullable()) {
185
0
        map_reader->_sub_readers[3] = std::move(null_reader);
186
0
    }
187
796
    map_reader->_meta_type = FieldType::OLAP_FIELD_TYPE_MAP;
188
796
    *reader = std::move(map_reader);
189
796
    return Status::OK();
190
796
}
191
192
Status ColumnReader::create_struct(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
193
                                   uint64_t num_rows, const io::FileReaderSPtr& file_reader,
194
0
                                   std::shared_ptr<ColumnReader>* reader) {
195
    // not support empty struct
196
0
    DCHECK(meta.children_columns_size() >= 1);
197
    // create struct column reader
198
0
    std::shared_ptr<ColumnReader> struct_reader(
199
0
            new ColumnReader(opts, meta, num_rows, file_reader));
200
0
    struct_reader->_sub_readers.reserve(meta.children_columns_size());
201
    // now we support struct column can add the children columns according to the schema-change behavior
202
0
    for (int i = 0; i < meta.children_columns_size(); i++) {
203
0
        std::shared_ptr<ColumnReader> sub_reader;
204
0
        RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(i),
205
0
                                             meta.children_columns(i).num_rows(), file_reader,
206
0
                                             &sub_reader));
207
0
        struct_reader->_sub_readers.push_back(std::move(sub_reader));
208
0
    }
209
0
    struct_reader->_meta_type = FieldType::OLAP_FIELD_TYPE_STRUCT;
210
0
    *reader = std::move(struct_reader);
211
0
    return Status::OK();
212
0
}
213
214
Status ColumnReader::create_agg_state(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
215
                                      uint64_t num_rows, const io::FileReaderSPtr& file_reader,
216
0
                                      std::shared_ptr<ColumnReader>* reader) {
217
0
    if (!meta.has_function_name()) { // meet old version ColumnMetaPB
218
0
        std::shared_ptr<ColumnReader> reader_local(
219
0
                new ColumnReader(opts, meta, num_rows, file_reader));
220
0
        RETURN_IF_ERROR(reader_local->init(&meta));
221
0
        *reader = std::move(reader_local);
222
0
        return Status::OK();
223
0
    }
224
225
0
    auto data_type = DataTypeFactory::instance().create_data_type(meta);
226
0
    const auto* agg_state_type = assert_cast<const DataTypeAggState*>(data_type.get());
227
0
    agg_state_type->check_function_compatibility(opts.be_exec_version);
228
0
    auto type = agg_state_type->get_serialized_type()->get_primitive_type();
229
230
0
    if (read_as_string(type)) {
231
0
        std::shared_ptr<ColumnReader> reader_local(
232
0
                new ColumnReader(opts, meta, num_rows, file_reader));
233
0
        RETURN_IF_ERROR(reader_local->init(&meta));
234
0
        *reader = std::move(reader_local);
235
0
        return Status::OK();
236
0
    } else if (type == PrimitiveType::TYPE_MAP) {
237
0
        return create_map(opts, meta, file_reader, reader);
238
0
    } else if (type == PrimitiveType::TYPE_ARRAY) {
239
0
        return create_array(opts, meta, file_reader, reader);
240
0
    } else if (type == PrimitiveType::TYPE_STRUCT) {
241
0
        return create_struct(opts, meta, num_rows, file_reader, reader);
242
0
    }
243
244
0
    return Status::InternalError("Not supported type: {}, serialized type: {}",
245
0
                                 agg_state_type->get_name(), int(type));
246
0
}
247
248
1.51k
bool ColumnReader::is_compaction_reader_type(ReaderType type) {
249
1.51k
    return type == ReaderType::READER_BASE_COMPACTION ||
250
1.51k
           type == ReaderType::READER_CUMULATIVE_COMPACTION ||
251
1.51k
           type == ReaderType::READER_COLD_DATA_COMPACTION ||
252
1.51k
           type == ReaderType::READER_SEGMENT_COMPACTION ||
253
1.51k
           type == ReaderType::READER_FULL_COMPACTION;
254
1.51k
}
255
256
Status ColumnReader::create(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
257
                            uint64_t num_rows, const io::FileReaderSPtr& file_reader,
258
11.9k
                            std::shared_ptr<ColumnReader>* reader) {
259
11.9k
    if (opts.const_value.has_value()) {
260
3
        *reader = std::make_shared<ConstantColumnReader>(*opts.const_value);
261
3
        return Status::OK();
262
3
    }
263
11.9k
    if (is_scalar_type((FieldType)meta.type())) {
264
10.3k
        std::shared_ptr<ColumnReader> reader_local(
265
10.3k
                new ColumnReader(opts, meta, num_rows, file_reader));
266
10.3k
        RETURN_IF_ERROR(reader_local->init(&meta));
267
10.3k
        *reader = std::move(reader_local);
268
10.3k
        return Status::OK();
269
10.3k
    } else {
270
1.56k
        auto type = (FieldType)meta.type();
271
1.56k
        switch (type) {
272
0
        case FieldType::OLAP_FIELD_TYPE_AGG_STATE: {
273
0
            return create_agg_state(opts, meta, num_rows, file_reader, reader);
274
0
        }
275
0
        case FieldType::OLAP_FIELD_TYPE_STRUCT: {
276
0
            return create_struct(opts, meta, num_rows, file_reader, reader);
277
0
        }
278
35
        case FieldType::OLAP_FIELD_TYPE_ARRAY: {
279
35
            return create_array(opts, meta, file_reader, reader);
280
0
        }
281
796
        case FieldType::OLAP_FIELD_TYPE_MAP: {
282
796
            return create_map(opts, meta, file_reader, reader);
283
0
        }
284
732
        case FieldType::OLAP_FIELD_TYPE_VARIANT: {
285
            // Read variant only root data using a single ColumnReader
286
732
            std::shared_ptr<ColumnReader> reader_local(
287
732
                    new ColumnReader(opts, meta, num_rows, file_reader));
288
732
            RETURN_IF_ERROR(reader_local->init(&meta));
289
732
            *reader = std::move(reader_local);
290
732
            return Status::OK();
291
732
        }
292
0
        default:
293
0
            return Status::NotSupported("unsupported type for ColumnReader: {}",
294
0
                                        std::to_string(int(type)));
295
1.56k
        }
296
1.56k
    }
297
11.9k
}
298
299
1.17k
ColumnReader::ColumnReader() = default;
300
301
ColumnReader::ColumnReader(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
302
                           uint64_t num_rows, io::FileReaderSPtr file_reader)
303
11.9k
        : _use_index_page_cache(!config::disable_storage_page_cache),
304
11.9k
          _opts(opts),
305
11.9k
          _num_rows(num_rows),
306
11.9k
          _file_reader(std::move(file_reader)),
307
11.9k
          _dict_encoding_type(UNKNOWN_DICT_ENCODING) {
308
11.9k
    _meta_length = meta.length();
309
11.9k
    _meta_type = (FieldType)meta.type();
310
11.9k
    if (_meta_type == FieldType::OLAP_FIELD_TYPE_ARRAY) {
311
35
        _meta_children_column_type = (FieldType)meta.children_columns(0).type();
312
35
    }
313
11.9k
    _data_type = DataTypeFactory::instance().create_data_type(meta);
314
11.9k
    _meta_is_nullable = meta.is_nullable();
315
11.9k
    _meta_dict_page = meta.dict_page();
316
11.9k
    _meta_compression = meta.compression();
317
11.9k
}
318
319
13.1k
ColumnReader::~ColumnReader() = default;
320
321
11.3k
int64_t ColumnReader::get_metadata_size() const {
322
11.3k
    return sizeof(ColumnReader) + (_segment_zone_map ? _segment_zone_map->ByteSizeLong() : 0);
323
11.3k
}
324
325
#ifdef BE_TEST
326
/// This function is only used in UT to verify the correctness of data read from zone map
327
/// See UT case 'SegCompactionMoWTest.SegCompactionInterleaveWithBig_ooooOOoOooooooooO'
328
/// be/test/olap/segcompaction_mow_test.cpp
329
20.4k
void ColumnReader::check_data_by_zone_map_for_test(const MutableColumnPtr& dst) const {
330
20.4k
    if (!_segment_zone_map) {
331
2.07k
        return;
332
2.07k
    }
333
334
18.3k
    const auto rows = dst->size();
335
18.3k
    if (rows == 0) {
336
0
        return;
337
0
    }
338
339
18.3k
    FieldType type = _type;
340
341
18.3k
    if (type != FieldType::OLAP_FIELD_TYPE_INT) {
342
2.93k
        return;
343
2.93k
    }
344
345
15.4k
    auto* non_nullable_column =
346
15.4k
            is_column_nullable(*dst)
347
15.4k
                    ? assert_cast<ColumnNullable*>(dst.get())->get_nested_column_ptr().get()
348
15.4k
                    : dst.get();
349
350
    /// Only verify when the destination column carries Field-accessible TYPE_INT data.
351
15.4k
    if (check_and_get_column<ColumnVector<TYPE_INT>>(non_nullable_column) == nullptr) {
352
0
        return;
353
0
    }
354
355
15.4k
    ZoneMap zone_map;
356
15.4k
    THROW_IF_ERROR(ZoneMap::from_proto(*_segment_zone_map, _data_type, zone_map));
357
358
15.4k
    if (zone_map.has_null) {
359
10
        return;
360
10
    }
361
362
22.1M
    for (size_t i = 0; i != rows; ++i) {
363
22.1M
        Field field;
364
22.1M
        dst->get(i, field);
365
22.1M
        DCHECK(!field.is_null());
366
22.1M
        const auto v = field.get<TYPE_INT>();
367
22.1M
        DCHECK_GE(v, zone_map.min_value.get<TYPE_INT>());
368
22.1M
        DCHECK_LE(v, zone_map.max_value.get<TYPE_INT>());
369
22.1M
    }
370
15.4k
}
371
#endif
372
373
11.0k
Status ColumnReader::init(const ColumnMetaPB* meta) {
374
11.0k
    _type = (FieldType)meta->type();
375
376
11.0k
    if (meta->has_be_exec_version()) {
377
7.96k
        _be_exec_version = meta->be_exec_version();
378
7.96k
    }
379
380
11.0k
    if (_type == FieldType::OLAP_FIELD_TYPE_NONE || _type == FieldType::OLAP_FIELD_TYPE_UNKNOWN) {
381
0
        return Status::NotSupported("unsupported typeinfo, type={}", meta->type());
382
0
    }
383
11.0k
    RETURN_IF_ERROR(EncodingInfo::get(_type, meta->encoding(), &_encoding_info));
384
385
29.1k
    for (int i = 0; i < meta->indexes_size(); i++) {
386
18.0k
        const auto& index_meta = meta->indexes(i);
387
18.0k
        switch (index_meta.type()) {
388
0
        case BITMAP_INDEX:
389
0
            break;
390
10.4k
        case ORDINAL_INDEX:
391
10.4k
            _ordinal_index.reset(
392
10.4k
                    new OrdinalIndexReader(_file_reader, _num_rows, index_meta.ordinal_index()));
393
10.4k
            break;
394
7.54k
        case ZONE_MAP_INDEX:
395
7.54k
            _segment_zone_map =
396
7.54k
                    std::make_unique<ZoneMapPB>(index_meta.zone_map_index().segment_zone_map());
397
7.54k
            _zone_map_index.reset(new ZoneMapIndexReader(
398
7.54k
                    _file_reader, index_meta.zone_map_index().page_zone_maps()));
399
7.54k
            break;
400
7
        case BLOOM_FILTER_INDEX:
401
7
            _bloom_filter_index.reset(
402
7
                    new BloomFilterIndexReader(_file_reader, index_meta.bloom_filter_index()));
403
7
            break;
404
0
        case NESTED_OFFSETS_INDEX:
405
0
            break;
406
0
        default:
407
0
            return Status::Corruption("Bad file {}: invalid column index type {}",
408
0
                                      _file_reader->path().native(), index_meta.type());
409
18.0k
        }
410
18.0k
    }
411
11.0k
    update_metadata_size();
412
413
    // ArrayColumnWriter writes a single empty array and flushes. In this scenario,
414
    // the item writer doesn't write any data and the corresponding ordinal index is empty.
415
11.0k
    if (_ordinal_index == nullptr && !is_empty()) {
416
0
        return Status::Corruption("Bad file {}: missing ordinal index for column {}",
417
0
                                  _file_reader->path().native(), meta->column_id());
418
0
    }
419
420
11.0k
    return Status::OK();
421
11.0k
}
422
423
Status ColumnReader::new_index_iterator(const std::shared_ptr<IndexFileReader>& index_file_reader,
424
                                        const TabletIndex* index_meta, const std::string& rowset_id,
425
                                        uint32_t segment_id, size_t rows_of_segment,
426
2.67k
                                        std::unique_ptr<IndexIterator>* iterator) {
427
2.67k
    RETURN_IF_ERROR(
428
2.67k
            _load_index(index_file_reader, index_meta, rowset_id, segment_id, rows_of_segment));
429
2.67k
    {
430
2.67k
        std::shared_lock<std::shared_mutex> rlock(_load_index_lock);
431
2.67k
        auto iter = _index_readers.find(index_meta->index_id());
432
2.67k
        if (iter != _index_readers.end()) {
433
2.67k
            if (iter->second != nullptr) {
434
2.67k
                RETURN_IF_ERROR(iter->second->new_iterator(iterator));
435
2.67k
            }
436
2.67k
        }
437
2.67k
    }
438
2.67k
    return Status::OK();
439
2.67k
}
440
441
Status ColumnReader::read_page(const ColumnIteratorOptions& iter_opts, const PagePointer& pp,
442
                               PageHandle* handle, Slice* page_body, PageFooterPB* footer,
443
13.8k
                               BlockCompressionCodec* codec) const {
444
13.8k
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().column_reader_read_page);
445
13.8k
    iter_opts.sanity_check();
446
13.8k
    PageReadOptions opts(iter_opts.io_ctx);
447
13.8k
    opts.verify_checksum = _opts.verify_checksum;
448
13.8k
    opts.use_page_cache = iter_opts.use_page_cache;
449
13.8k
    opts.kept_in_memory = _opts.kept_in_memory;
450
13.8k
    opts.type = iter_opts.type;
451
13.8k
    opts.file_reader = iter_opts.file_reader;
452
13.8k
    opts.page_pointer = pp;
453
13.8k
    opts.codec = codec;
454
13.8k
    opts.stats = iter_opts.stats;
455
13.8k
    opts.encoding_info = _encoding_info;
456
457
13.8k
    return PageIO::read_and_decompress_page(opts, handle, page_body, footer);
458
13.8k
}
459
460
Status ColumnReader::get_row_ranges_by_zone_map(
461
        const AndBlockColumnPredicate* col_predicates,
462
        const std::vector<std::shared_ptr<const ColumnPredicate>>* delete_predicates,
463
64
        RowRanges* row_ranges, const ColumnIteratorOptions& iter_opts) {
464
64
    std::vector<uint32_t> page_indexes;
465
64
    RETURN_IF_ERROR(
466
64
            _get_filtered_pages(col_predicates, delete_predicates, &page_indexes, iter_opts));
467
64
    RETURN_IF_ERROR(_calculate_row_ranges(page_indexes, row_ranges, iter_opts));
468
64
    return Status::OK();
469
64
}
470
471
0
Status ColumnReader::next_batch_of_zone_map(size_t* n, MutableColumnPtr& dst) const {
472
0
    if (_segment_zone_map == nullptr) {
473
0
        return Status::InternalError("segment zonemap not exist");
474
0
    }
475
    // TODO: this work to get min/max value seems should only do once
476
0
    ZoneMap zone_map;
477
0
    RETURN_IF_ERROR(ZoneMap::from_proto(*_segment_zone_map, _data_type, zone_map));
478
479
0
    dst->reserve(*n);
480
0
    if (!zone_map.has_not_null) {
481
0
        assert_cast<ColumnNullable&>(*dst).insert_many_defaults(*n);
482
0
        return Status::OK();
483
0
    }
484
0
    dst->insert(zone_map.max_value);
485
0
    for (int i = 1; i < *n; ++i) {
486
0
        dst->insert(zone_map.min_value);
487
0
    }
488
0
    return Status::OK();
489
0
}
490
491
Status ColumnReader::match_condition(const AndBlockColumnPredicate* col_predicates,
492
71
                                     bool* matched) const {
493
71
    *matched = true;
494
71
    if (_zone_map_index == nullptr) {
495
0
        return Status::OK();
496
0
    }
497
71
    ZoneMap zone_map;
498
71
    RETURN_IF_ERROR(ZoneMap::from_proto(*_segment_zone_map, _data_type, zone_map));
499
500
71
    *matched = _zone_map_match_condition(zone_map, col_predicates);
501
71
    return Status::OK();
502
71
}
503
504
Status ConstantColumnReader::match_condition(const AndBlockColumnPredicate* col_predicates,
505
3
                                             bool* matched) const {
506
3
    ZoneMap zone_map;
507
3
    zone_map.min_value = _value;
508
3
    zone_map.max_value = _value;
509
3
    zone_map.has_not_null = !_value.is_null();
510
    // evaluate_and returns false iff no value in [min, max] (i.e. the real constant) can satisfy
511
    // the predicates; predicates that don't support zonemap conservatively return true.
512
3
    *matched = col_predicates->evaluate_and(zone_map);
513
3
    return Status::OK();
514
3
}
515
516
Status ColumnReader::prune_predicates_by_zone_map(
517
        std::vector<std::shared_ptr<ColumnPredicate>>& predicates, const int column_id,
518
64
        bool* pruned) const {
519
64
    *pruned = false;
520
64
    if (_zone_map_index == nullptr) {
521
44
        return Status::OK();
522
44
    }
523
524
20
    ZoneMap zone_map;
525
20
    RETURN_IF_ERROR(ZoneMap::from_proto(*_segment_zone_map, _data_type, zone_map));
526
20
    if (zone_map.pass_all) {
527
0
        return Status::OK();
528
0
    }
529
530
40
    for (auto it = predicates.begin(); it != predicates.end();) {
531
20
        auto predicate = *it;
532
20
        if (predicate->column_id() == column_id && predicate->is_always_true(zone_map)) {
533
0
            *pruned = true;
534
0
            it = predicates.erase(it);
535
20
        } else {
536
20
            ++it;
537
20
        }
538
20
    }
539
20
    return Status::OK();
540
20
}
541
542
bool ColumnReader::_zone_map_match_condition(const ZoneMap& zone_map,
543
78
                                             const AndBlockColumnPredicate* col_predicates) const {
544
78
    if (zone_map.pass_all) {
545
0
        return true;
546
0
    }
547
548
78
    return col_predicates->evaluate_and(zone_map);
549
78
}
550
551
Status ColumnReader::_get_filtered_pages(
552
        const AndBlockColumnPredicate* col_predicates,
553
        const std::vector<std::shared_ptr<const ColumnPredicate>>* delete_predicates,
554
64
        std::vector<uint32_t>* page_indexes, const ColumnIteratorOptions& iter_opts) {
555
64
    RETURN_IF_ERROR(_load_zone_map_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
556
557
64
    const std::vector<ZoneMapPB>& zone_maps = _zone_map_index->page_zone_maps();
558
64
    size_t page_size = _zone_map_index->num_pages();
559
128
    for (size_t i = 0; i < page_size; ++i) {
560
64
        if (zone_maps[i].pass_all()) {
561
57
            page_indexes->push_back(cast_set<uint32_t>(i));
562
57
        } else {
563
7
            segment_v2::ZoneMap zone_map;
564
7
            RETURN_IF_ERROR(ZoneMap::from_proto(zone_maps[i], _data_type, zone_map));
565
7
            if (_zone_map_match_condition(zone_map, col_predicates)) {
566
7
                bool should_read = true;
567
7
                if (delete_predicates != nullptr) {
568
0
                    for (auto del_pred : *delete_predicates) {
569
                        // TODO: Both `min_value` and `max_value` should be 0 or neither should be 0.
570
                        //  So nullable only need to judge once.
571
0
                        if (del_pred->evaluate_del(zone_map)) {
572
0
                            should_read = false;
573
0
                            break;
574
0
                        }
575
0
                    }
576
0
                }
577
7
                if (should_read) {
578
7
                    page_indexes->push_back(cast_set<uint32_t>(i));
579
7
                }
580
7
            }
581
7
        }
582
64
    }
583
64
    VLOG(1) << "total-pages: " << page_size << " not-filtered-pages: " << page_indexes->size()
584
64
            << " filtered-percent:"
585
64
            << 1.0 - (static_cast<double>(page_indexes->size()) /
586
64
                      (static_cast<double>(page_size) * 1.0));
587
64
    return Status::OK();
588
64
}
589
590
Status ColumnReader::_calculate_row_ranges(const std::vector<uint32_t>& page_indexes,
591
                                           RowRanges* row_ranges,
592
64
                                           const ColumnIteratorOptions& iter_opts) {
593
64
    row_ranges->clear();
594
64
    RETURN_IF_ERROR(_load_ordinal_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
595
64
    for (auto i : page_indexes) {
596
64
        ordinal_t page_first_id = _ordinal_index->get_first_ordinal(i);
597
64
        ordinal_t page_last_id = _ordinal_index->get_last_ordinal(i);
598
64
        RowRanges page_row_ranges(RowRanges::create_single(page_first_id, page_last_id + 1));
599
64
        RowRanges::ranges_union(*row_ranges, page_row_ranges, row_ranges);
600
64
    }
601
64
    return Status::OK();
602
64
}
603
604
Status ColumnReader::get_row_ranges_by_bloom_filter(const AndBlockColumnPredicate* col_predicates,
605
                                                    RowRanges* row_ranges,
606
3
                                                    const ColumnIteratorOptions& iter_opts) {
607
3
    RETURN_IF_ERROR(_load_ordinal_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
608
3
    RETURN_IF_ERROR(
609
3
            _load_bloom_filter_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
610
3
    RowRanges bf_row_ranges;
611
3
    std::unique_ptr<BloomFilterIndexIterator> bf_iter;
612
3
    RETURN_IF_ERROR(
613
3
            _bloom_filter_index->new_iterator(&bf_iter, iter_opts.stats, &iter_opts.io_ctx));
614
3
    size_t range_size = row_ranges->range_size();
615
    // get covered page ids
616
3
    std::set<uint32_t> page_ids;
617
6
    for (int i = 0; i < range_size; ++i) {
618
3
        int64_t from = row_ranges->get_range_from(i);
619
3
        int64_t idx = from;
620
3
        int64_t to = row_ranges->get_range_to(i);
621
3
        auto iter = _ordinal_index->seek_at_or_before(from);
622
6
        while (idx < to && iter.valid()) {
623
3
            page_ids.insert(iter.page_index());
624
3
            idx = iter.last_ordinal() + 1;
625
3
            iter.next();
626
3
        }
627
3
    }
628
3
    for (auto& pid : page_ids) {
629
3
        std::unique_ptr<BloomFilter> bf;
630
3
        RETURN_IF_ERROR(bf_iter->read_bloom_filter(pid, &bf));
631
3
        if (col_predicates->evaluate_and(bf.get())) {
632
0
            bf_row_ranges.add(RowRange(_ordinal_index->get_first_ordinal(pid),
633
0
                                       _ordinal_index->get_last_ordinal(pid) + 1));
634
0
        }
635
3
    }
636
3
    RowRanges::ranges_intersection(*row_ranges, bf_row_ranges, row_ranges);
637
3
    return Status::OK();
638
3
}
639
640
Status ColumnReader::_load_ordinal_index(bool use_page_cache, bool kept_in_memory,
641
9.12k
                                         const ColumnIteratorOptions& iter_opts) {
642
9.12k
    if (!_ordinal_index) {
643
0
        return Status::InternalError("ordinal_index not inited");
644
0
    }
645
9.12k
    return _ordinal_index->load(use_page_cache, kept_in_memory, iter_opts.stats, &iter_opts.io_ctx);
646
9.12k
}
647
648
Status ColumnReader::_load_zone_map_index(bool use_page_cache, bool kept_in_memory,
649
65
                                          const ColumnIteratorOptions& iter_opts) {
650
65
    if (_zone_map_index != nullptr) {
651
65
        return _zone_map_index->load(use_page_cache, kept_in_memory, iter_opts.stats,
652
65
                                     &iter_opts.io_ctx);
653
65
    }
654
0
    return Status::OK();
655
65
}
656
657
8
Status ColumnReader::get_segment_zone_map(segment_v2::ZoneMap* zone_map) const {
658
8
    DORIS_CHECK(zone_map != nullptr);
659
8
    DORIS_CHECK(_segment_zone_map != nullptr);
660
8
    return ZoneMap::from_proto(*_segment_zone_map, _data_type, *zone_map);
661
8
}
662
663
1
Status ConstantColumnReader::get_segment_zone_map(segment_v2::ZoneMap* zone_map) const {
664
1
    zone_map->min_value = _value;
665
1
    zone_map->max_value = _value;
666
1
    zone_map->has_not_null = !_value.is_null();
667
1
    return Status::OK();
668
1
}
669
670
Status ColumnReader::get_page_zone_maps(const ColumnIteratorOptions& iter_opts,
671
1
                                        const std::vector<ZoneMapPB>** zone_maps) {
672
1
    DORIS_CHECK(zone_maps != nullptr);
673
1
    if (_zone_map_index == nullptr) {
674
0
        *zone_maps = nullptr;
675
0
        return Status::OK();
676
0
    }
677
1
    RETURN_IF_ERROR(_load_zone_map_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
678
1
    *zone_maps = &_zone_map_index->page_zone_maps();
679
1
    return Status::OK();
680
1
}
681
682
Status ColumnReader::get_row_range_for_page(uint32_t page_index,
683
                                            const ColumnIteratorOptions& iter_opts,
684
8
                                            RowRange* row_range) {
685
8
    DORIS_CHECK(row_range != nullptr);
686
8
    RETURN_IF_ERROR(_load_ordinal_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
687
8
    DORIS_CHECK(page_index < _ordinal_index->num_data_pages());
688
8
    *row_range = RowRange(_ordinal_index->get_first_ordinal(page_index),
689
8
                          _ordinal_index->get_last_ordinal(page_index) + 1);
690
8
    return Status::OK();
691
8
}
692
693
Status ColumnReader::_load_index(const std::shared_ptr<IndexFileReader>& index_file_reader,
694
                                 const TabletIndex* index_meta, const std::string& rowset_id,
695
2.67k
                                 uint32_t segment_id, size_t rows_of_segment) {
696
2.67k
    std::unique_lock<std::shared_mutex> wlock(_load_index_lock);
697
698
2.67k
    if (index_meta == nullptr) {
699
0
        return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
700
0
                "Failed to load inverted index: index metadata is null");
701
0
    }
702
703
2.67k
    auto it = _index_readers.find(index_meta->index_id());
704
2.67k
    if (it != _index_readers.end()) {
705
0
        return Status::OK();
706
0
    }
707
708
2.67k
    bool should_analyzer =
709
2.67k
            inverted_index::InvertedIndexAnalyzer::should_analyzer(index_meta->properties());
710
711
2.67k
    FieldType type;
712
2.67k
    if (_meta_type == FieldType::OLAP_FIELD_TYPE_ARRAY) {
713
22
        type = _meta_children_column_type;
714
2.65k
    } else {
715
2.65k
        type = _type;
716
2.65k
    }
717
718
2.67k
    if (index_meta->index_type() == IndexType::ANN) {
719
1
        _index_readers[index_meta->index_id()] = std::make_shared<AnnIndexReader>(
720
1
                index_meta, index_file_reader, rowset_id, segment_id, rows_of_segment);
721
1
        return Status::OK();
722
1
    }
723
724
2.67k
    IndexReaderPtr index_reader;
725
726
2.67k
    if (is_string_type(type)) {
727
2.24k
        if (should_analyzer) {
728
1.69k
            try {
729
1.69k
                index_reader = FullTextIndexReader::create_shared(index_meta, index_file_reader);
730
1.69k
            } catch (const CLuceneError& e) {
731
0
                return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
732
0
                        "create FullTextIndexReader error: {}", e.what());
733
0
            }
734
1.69k
        } else {
735
545
            try {
736
545
                index_reader =
737
545
                        StringTypeInvertedIndexReader::create_shared(index_meta, index_file_reader);
738
545
            } catch (const CLuceneError& e) {
739
0
                return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
740
0
                        "create StringTypeInvertedIndexReader error: {}", e.what());
741
0
            }
742
545
        }
743
2.24k
    } else if (is_numeric_type(type)) {
744
433
        try {
745
433
            index_reader = BkdIndexReader::create_shared(index_meta, index_file_reader);
746
433
        } catch (const CLuceneError& e) {
747
0
            return Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
748
0
                    "create BkdIndexReader error: {}", e.what());
749
0
        }
750
433
    } else {
751
0
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
752
0
                "Field type {} is not supported for inverted index", type);
753
0
    }
754
2.67k
    _index_readers[index_meta->index_id()] = index_reader;
755
2.67k
    return Status::OK();
756
2.67k
}
757
758
48
bool ColumnReader::has_bloom_filter_index(bool ngram) const {
759
48
    if (_bloom_filter_index == nullptr) return false;
760
761
3
    if (ngram) {
762
0
        return _bloom_filter_index->algorithm() == BloomFilterAlgorithmPB::NGRAM_BLOOM_FILTER;
763
3
    } else {
764
3
        return _bloom_filter_index->algorithm() != BloomFilterAlgorithmPB::NGRAM_BLOOM_FILTER;
765
3
    }
766
3
}
767
768
Status ColumnReader::_load_bloom_filter_index(bool use_page_cache, bool kept_in_memory,
769
3
                                              const ColumnIteratorOptions& iter_opts) {
770
3
    if (_bloom_filter_index != nullptr) {
771
3
        return _bloom_filter_index->load(use_page_cache, kept_in_memory, iter_opts.stats,
772
3
                                         &iter_opts.io_ctx);
773
3
    }
774
0
    return Status::OK();
775
3
}
776
777
Status ColumnReader::seek_at_or_before(ordinal_t ordinal, OrdinalPageIndexIterator* iter,
778
9.04k
                                       const ColumnIteratorOptions& iter_opts) {
779
9.04k
    RETURN_IF_ERROR(_load_ordinal_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
780
9.04k
    *iter = _ordinal_index->seek_at_or_before(ordinal);
781
9.04k
    if (!iter->valid()) {
782
0
        return Status::NotFound("Failed to seek to ordinal {}, ", ordinal);
783
0
    }
784
9.04k
    return Status::OK();
785
9.04k
}
786
787
Status ColumnReader::get_ordinal_index_reader(OrdinalIndexReader*& reader,
788
0
                                              OlapReaderStatistics* index_load_stats) {
789
0
    CHECK(_ordinal_index) << fmt::format("ordinal index is null for column reader of type {}",
790
0
                                         std::to_string(int(_meta_type)));
791
0
    RETURN_IF_ERROR(
792
0
            _ordinal_index->load(_use_index_page_cache, _opts.kept_in_memory, index_load_stats));
793
0
    reader = _ordinal_index.get();
794
0
    return Status::OK();
795
0
}
796
797
1.74k
Status ColumnReader::new_iterator(ColumnIteratorUPtr* iterator, const TabletColumn* tablet_column) {
798
1.74k
    return new_iterator(iterator, tablet_column, nullptr);
799
1.74k
}
800
801
Status ColumnReader::new_iterator(ColumnIteratorUPtr* iterator, const TabletColumn* tablet_column,
802
8.87k
                                  const StorageReadOptions* opt) {
803
8.87k
    if (is_empty()) {
804
150
        *iterator = std::make_unique<EmptyFileColumnIterator>();
805
150
        return Status::OK();
806
150
    }
807
8.72k
    if (is_scalar_type(_meta_type)) {
808
8.41k
        if (is_string_type(_meta_type)) {
809
2.91k
            *iterator = std::make_unique<StringFileColumnIterator>(shared_from_this());
810
5.49k
        } else {
811
5.49k
            *iterator = std::make_unique<FileColumnIterator>(shared_from_this());
812
5.49k
        }
813
8.41k
        (*iterator)->set_column_name(tablet_column ? tablet_column->name() : "");
814
8.41k
        return Status::OK();
815
8.41k
    } else {
816
315
        auto type = _meta_type;
817
315
        switch (type) {
818
0
        case FieldType::OLAP_FIELD_TYPE_AGG_STATE: {
819
0
            return new_agg_state_iterator(iterator);
820
0
        }
821
0
        case FieldType::OLAP_FIELD_TYPE_STRUCT: {
822
0
            return new_struct_iterator(iterator, tablet_column);
823
0
        }
824
30
        case FieldType::OLAP_FIELD_TYPE_ARRAY: {
825
30
            return new_array_iterator(iterator, tablet_column);
826
0
        }
827
285
        case FieldType::OLAP_FIELD_TYPE_MAP: {
828
285
            return new_map_iterator(iterator, tablet_column);
829
0
        }
830
0
        default:
831
0
            return Status::NotSupported("unsupported type to create iterator: {}",
832
0
                                        std::to_string(int(type)));
833
315
        }
834
315
    }
835
8.72k
}
836
837
0
Status ColumnReader::new_agg_state_iterator(ColumnIteratorUPtr* iterator) {
838
0
    *iterator = std::make_unique<FileColumnIterator>(shared_from_this());
839
0
    return Status::OK();
840
0
}
841
842
Status ColumnReader::new_array_iterator(ColumnIteratorUPtr* iterator,
843
30
                                        const TabletColumn* tablet_column) {
844
30
    ColumnIteratorUPtr item_iterator;
845
30
    RETURN_IF_ERROR(_sub_readers[0]->new_iterator(
846
30
            &item_iterator, tablet_column && tablet_column->get_subtype_count() > 0
847
30
                                    ? &tablet_column->get_sub_column(0)
848
30
                                    : nullptr));
849
850
30
    item_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(0).name() : "");
851
852
30
    ColumnIteratorUPtr offset_iterator;
853
30
    RETURN_IF_ERROR(_sub_readers[1]->new_iterator(&offset_iterator, nullptr));
854
30
    auto* file_iter = static_cast<FileColumnIterator*>(offset_iterator.release());
855
30
    OffsetFileColumnIteratorUPtr ofcIter = std::make_unique<OffsetFileColumnIterator>(
856
30
            std::unique_ptr<FileColumnIterator>(file_iter));
857
858
30
    ColumnIteratorUPtr null_iterator;
859
30
    if (is_nullable()) {
860
28
        RETURN_IF_ERROR(_sub_readers[2]->new_iterator(&null_iterator, nullptr));
861
28
    }
862
30
    *iterator = std::make_unique<ArrayFileColumnIterator>(shared_from_this(), std::move(ofcIter),
863
30
                                                          std::move(item_iterator),
864
30
                                                          std::move(null_iterator));
865
30
    return Status::OK();
866
30
}
867
868
Status ColumnReader::new_map_iterator(ColumnIteratorUPtr* iterator,
869
285
                                      const TabletColumn* tablet_column) {
870
285
    ColumnIteratorUPtr key_iterator;
871
285
    RETURN_IF_ERROR(_sub_readers[0]->new_iterator(
872
285
            &key_iterator, tablet_column && tablet_column->get_subtype_count() > 1
873
285
                                   ? &tablet_column->get_sub_column(0)
874
285
                                   : nullptr));
875
285
    key_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(0).name() : "");
876
285
    ColumnIteratorUPtr val_iterator;
877
285
    RETURN_IF_ERROR(_sub_readers[1]->new_iterator(
878
285
            &val_iterator, tablet_column && tablet_column->get_subtype_count() > 1
879
285
                                   ? &tablet_column->get_sub_column(1)
880
285
                                   : nullptr));
881
285
    val_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(1).name() : "");
882
285
    ColumnIteratorUPtr offsets_iterator;
883
285
    RETURN_IF_ERROR(_sub_readers[2]->new_iterator(&offsets_iterator, nullptr));
884
285
    auto* file_iter = static_cast<FileColumnIterator*>(offsets_iterator.release());
885
285
    OffsetFileColumnIteratorUPtr ofcIter = std::make_unique<OffsetFileColumnIterator>(
886
285
            std::unique_ptr<FileColumnIterator>(file_iter));
887
888
285
    ColumnIteratorUPtr null_iterator;
889
285
    if (is_nullable()) {
890
0
        RETURN_IF_ERROR(_sub_readers[3]->new_iterator(&null_iterator, nullptr));
891
0
    }
892
285
    *iterator = std::make_unique<MapFileColumnIterator>(
893
285
            shared_from_this(), std::move(null_iterator), std::move(ofcIter),
894
285
            std::move(key_iterator), std::move(val_iterator));
895
285
    return Status::OK();
896
285
}
897
898
Status ColumnReader::new_struct_iterator(ColumnIteratorUPtr* iterator,
899
0
                                         const TabletColumn* tablet_column) {
900
0
    std::vector<ColumnIteratorUPtr> sub_column_iterators;
901
0
    size_t child_size = is_nullable() ? _sub_readers.size() - 1 : _sub_readers.size();
902
0
    size_t tablet_column_size = tablet_column ? tablet_column->get_sub_columns().size() : 0;
903
0
    sub_column_iterators.reserve(child_size);
904
905
0
    for (uint64_t i = 0; i < child_size; i++) {
906
0
        ColumnIteratorUPtr sub_column_iterator;
907
0
        RETURN_IF_ERROR(_sub_readers[i]->new_iterator(
908
0
                &sub_column_iterator, tablet_column ? &tablet_column->get_sub_column(i) : nullptr));
909
0
        sub_column_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(i).name()
910
0
                                                           : "");
911
0
        sub_column_iterators.emplace_back(std::move(sub_column_iterator));
912
0
    }
913
914
    // create default_iterator for schema-change behavior which increase column
915
0
    for (size_t i = child_size; i < tablet_column_size; i++) {
916
0
        TabletColumn column = tablet_column->get_sub_column(i);
917
0
        ColumnIteratorUPtr it;
918
0
        RETURN_IF_ERROR(Segment::new_default_iterator(column, &it));
919
0
        it->set_column_name(column.name());
920
0
        sub_column_iterators.emplace_back(std::move(it));
921
0
    }
922
923
0
    ColumnIteratorUPtr null_iterator;
924
0
    if (is_nullable()) {
925
0
        RETURN_IF_ERROR(_sub_readers[child_size]->new_iterator(&null_iterator, nullptr));
926
0
    }
927
0
    *iterator = std::make_unique<StructFileColumnIterator>(
928
0
            shared_from_this(), std::move(null_iterator), std::move(sub_column_iterators));
929
0
    return Status::OK();
930
0
}
931
932
5
void ColumnIterator::_convert_to_place_holder_column(MutableColumnPtr& dst, size_t count) {
933
5
    if (_read_phase == ReadPhase::LAZY) {
934
1
        return;
935
4
    } else if (_read_requirement == ReadRequirement::LAZY_OUTPUT &&
936
4
               _read_phase == ReadPhase::PREDICATE) {
937
        // This branch is for non-predicate columns that still have to appear in the
938
        // predicate-phase block so row filtering can keep all block columns aligned.
939
        // Columns already marked PREDICATE are read normally, and SKIP/NORMAL
940
        // columns do not participate in lazy materialization.
941
3
        _has_place_holder_column = true;
942
3
    }
943
944
4
    dst->insert_many_defaults(count);
945
4
}
946
947
24.2k
void ColumnIterator::_recovery_from_place_holder_column(MutableColumnPtr& dst) {
948
24.2k
    if (_read_phase == ReadPhase::LAZY && _has_place_holder_column) {
949
3
        dst->clear();
950
3
        _has_place_holder_column = false;
951
3
    }
952
24.2k
}
953
954
Result<TColumnAccessPaths> ColumnIterator::_get_sub_access_paths(
955
183
        TColumnAccessPaths sub_access_paths, bool is_predicate) {
956
    // Access paths passed to a complex iterator always start with the current
957
    // column name. Strip that component and return the remaining child-relative
958
    // paths to the caller. For example, when this iterator is for column `s`,
959
    // path `s.a.b` is converted to `a.b` and then dispatched to child `a`.
960
    //
961
    // If stripping the current column consumes the whole path, the current
962
    // iterator itself is requested rather than one of its children. Mark the
963
    // current iterator according to the path source: predicate paths must be read
964
    // in the predicate phase, while all/output paths become lazy output targets.
965
    // Empty or mismatched paths indicate an FE/BE access-path contract violation.
966
339
    for (auto it = sub_access_paths.begin(); it != sub_access_paths.end();) {
967
161
        TColumnAccessPath& name_path = *it;
968
161
        if (name_path.data_access_path.path.empty()) {
969
2
            return ResultError(Status::InternalError(
970
2
                    "Invalid access path for column '{}': path is empty", _column_name));
971
2
        }
972
973
159
        if (!StringCaseEqual()(name_path.data_access_path.path[0], _column_name)) {
974
3
            return ResultError(Status::InternalError(
975
3
                    R"(Invalid access path for column: expected name "{}", got "{}")", _column_name,
976
3
                    name_path.data_access_path.path[0]));
977
3
        }
978
979
156
        name_path.data_access_path.path.erase(name_path.data_access_path.path.begin());
980
156
        if (!name_path.data_access_path.path.empty()) {
981
130
            ++it;
982
130
        } else {
983
26
            if (is_predicate) {
984
7
                set_read_requirement(ReadRequirement::PREDICATE);
985
19
            } else {
986
19
                set_lazy_output_requirement();
987
19
            }
988
26
            it = sub_access_paths.erase(it);
989
26
        }
990
156
    }
991
178
    return sub_access_paths;
992
183
}
993
994
///====================== MapFileColumnIterator ============================////
995
MapFileColumnIterator::MapFileColumnIterator(std::shared_ptr<ColumnReader> reader,
996
                                             ColumnIteratorUPtr null_iterator,
997
                                             OffsetFileColumnIteratorUPtr offsets_iterator,
998
                                             ColumnIteratorUPtr key_iterator,
999
                                             ColumnIteratorUPtr val_iterator)
1000
318
        : _map_reader(reader),
1001
318
          _offsets_iterator(std::move(offsets_iterator)),
1002
318
          _key_iterator(std::move(key_iterator)),
1003
318
          _val_iterator(std::move(val_iterator)) {
1004
318
    if (_map_reader->is_nullable()) {
1005
2
        _null_iterator = std::move(null_iterator);
1006
2
    }
1007
318
}
1008
1009
281
Status MapFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1010
281
    if (_read_requirement == ReadRequirement::SKIP) {
1011
0
        DLOG(INFO) << "Map column iterator column " << _column_name << " skip reading.";
1012
0
        return Status::OK();
1013
0
    }
1014
281
    RETURN_IF_ERROR(_key_iterator->init(opts));
1015
281
    RETURN_IF_ERROR(_val_iterator->init(opts));
1016
281
    RETURN_IF_ERROR(_offsets_iterator->init(opts));
1017
281
    if (_map_reader->is_nullable()) {
1018
0
        RETURN_IF_ERROR(_null_iterator->init(opts));
1019
0
    }
1020
281
    return Status::OK();
1021
281
}
1022
1023
269
Status MapFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
1024
269
    if (!need_to_read()) {
1025
0
        DLOG(INFO) << "Map column iterator column " << _column_name << " skip reading.";
1026
0
        return Status::OK();
1027
0
    }
1028
1029
269
    if (read_null_map_only()) {
1030
        // In NULL_MAP_ONLY mode, only seek the null iterator; skip offset/key/val iterators
1031
0
        if (_map_reader->is_nullable() && _null_iterator) {
1032
0
            RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1033
0
        }
1034
0
        return Status::OK();
1035
0
    }
1036
1037
269
    if (_map_reader->is_nullable()) {
1038
0
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1039
0
    }
1040
269
    RETURN_IF_ERROR(_offsets_iterator->seek_to_ordinal(ord));
1041
269
    if (read_offset_only()) {
1042
        // In OFFSET_ONLY mode, key/value iterators are SKIP, no need to seek them
1043
0
        return Status::OK();
1044
0
    }
1045
    // here to use offset info
1046
269
    ordinal_t offset = 0;
1047
269
    RETURN_IF_ERROR(_offsets_iterator->_peek_one_offset(&offset));
1048
269
    RETURN_IF_ERROR(_key_iterator->seek_to_ordinal(offset));
1049
269
    RETURN_IF_ERROR(_val_iterator->seek_to_ordinal(offset));
1050
269
    return Status::OK();
1051
269
}
1052
1053
0
Status MapFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
1054
0
    RETURN_IF_ERROR(_offsets_iterator->init_prefetcher(params));
1055
0
    if (_map_reader->is_nullable()) {
1056
0
        RETURN_IF_ERROR(_null_iterator->init_prefetcher(params));
1057
0
    }
1058
0
    RETURN_IF_ERROR(_key_iterator->init_prefetcher(params));
1059
0
    RETURN_IF_ERROR(_val_iterator->init_prefetcher(params));
1060
0
    return Status::OK();
1061
0
}
1062
1063
void MapFileColumnIterator::collect_prefetchers(
1064
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
1065
1
        PrefetcherInitMethod init_method) {
1066
1
    if (!need_to_read()) {
1067
0
        return;
1068
0
    }
1069
1
    if (!read_null_map_only()) {
1070
1
        _offsets_iterator->collect_prefetchers(prefetchers, init_method);
1071
1
    }
1072
1
    if (_map_reader->is_nullable()) {
1073
1
        _null_iterator->collect_prefetchers(prefetchers, init_method);
1074
1
    }
1075
1
    if (read_offset_only() || read_null_map_only()) {
1076
0
        return;
1077
0
    }
1078
    // the actual data pages to read of key/value column depends on the read result of offset column,
1079
    // so we can't init prefetch blocks according to rowids, just prefetch all data blocks here.
1080
1
    if (_key_iterator->need_to_read()) {
1081
1
        _key_iterator->collect_prefetchers(prefetchers, PrefetcherInitMethod::ALL_DATA_BLOCKS);
1082
1
    }
1083
1
    if (_val_iterator->need_to_read()) {
1084
1
        _val_iterator->collect_prefetchers(prefetchers, PrefetcherInitMethod::ALL_DATA_BLOCKS);
1085
1
    }
1086
1
}
1087
1088
269
Status MapFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1089
269
    if (!need_to_read()) {
1090
0
        DLOG(INFO) << "Map column iterator column " << _column_name << " skip reading.";
1091
0
        _convert_to_place_holder_column(dst, *n);
1092
0
        return Status::OK();
1093
0
    }
1094
1095
269
    _recovery_from_place_holder_column(dst);
1096
1097
269
    if (read_null_map_only()) {
1098
        // NULL_MAP_ONLY mode: read null map, fill nested ColumnMap with empty defaults
1099
1
        DORIS_CHECK(is_column_nullable(*dst));
1100
1
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
1101
1
        auto null_map_ptr = nullable_col.get_null_map_column_ptr();
1102
1
        size_t num_read = *n;
1103
1
        if (_null_iterator) {
1104
1
            bool null_signs_has_null = false;
1105
1
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
1106
1
            RETURN_IF_ERROR(
1107
1
                    _null_iterator->next_batch(&num_read, null_map_column, &null_signs_has_null));
1108
1
        } else {
1109
            // schema-change: column became nullable but old segment has no null data
1110
0
            null_map_ptr->insert_many_vals(0, num_read);
1111
0
        }
1112
1
        DCHECK(num_read == *n);
1113
        // fill nested ColumnMap with empty (zero-element) maps
1114
1
        auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
1115
1
                nullable_col.get_nested_column());
1116
1
        column_map.insert_many_defaults(num_read);
1117
1
        *has_null = true;
1118
1
        return Status::OK();
1119
1
    }
1120
1121
268
    auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
1122
268
            is_column_nullable(*dst) ? static_cast<ColumnNullable&>(*dst).get_nested_column()
1123
268
                                     : *dst);
1124
268
    const bool read_meta_columns = need_to_read_meta_columns();
1125
268
    MutableColumnPtr column_offsets_ptr;
1126
268
    if (read_meta_columns) {
1127
268
        column_offsets_ptr = IColumn::mutate(std::move(column_map.get_offsets_ptr()));
1128
268
    } else {
1129
        // The parent offsets were already materialized in the predicate phase, so
1130
        // they must not be appended to dst again. We still read offsets into a
1131
        // temporary column here: this sequential path may be serving a nested
1132
        // lazy read after seek_to_ordinal(), and the storage offsets are needed to
1133
        // compute how many key/value elements to read from the current source
1134
        // ordinal. The existing dst offsets only describe the filtered output
1135
        // shape and do not track the current source ordinal consumed by this
1136
        // iterator call.
1137
0
        const auto base_offset =
1138
0
                column_map.get_offsets().empty() ? 0 : column_map.get_offsets().back();
1139
0
        column_offsets_ptr = ColumnMap::COffsets::create();
1140
0
        assert_cast<ColumnOffset64&, TypeCheckOnRelease::DISABLE>(*column_offsets_ptr)
1141
0
                .insert_value(base_offset);
1142
0
    }
1143
268
    Defer defer_offsets {[&] {
1144
268
        if (read_meta_columns) {
1145
268
            auto typed_column_offsets_ptr = ColumnMap::COffsets::cast_to_column_mutptr(
1146
268
                    assert_cast<ColumnMap::COffsets*, TypeCheckOnRelease::DISABLE>(
1147
268
                            column_offsets_ptr.get()));
1148
268
            column_offsets_ptr = nullptr;
1149
268
            column_map.get_offsets_ptr() = std::move(typed_column_offsets_ptr);
1150
268
        }
1151
268
    }};
1152
268
    bool offsets_has_null = false;
1153
268
    ssize_t start = column_offsets_ptr->size();
1154
268
    RETURN_IF_ERROR(_offsets_iterator->next_batch(n, column_offsets_ptr, &offsets_has_null));
1155
268
    if (*n == 0) {
1156
0
        return Status::OK();
1157
0
    }
1158
268
    auto& column_offsets = static_cast<ColumnArray::ColumnOffsets&>(*column_offsets_ptr);
1159
268
    RETURN_IF_ERROR(_offsets_iterator->_calculate_offsets(start, column_offsets));
1160
268
    DCHECK(column_offsets.get_data().back() >= column_offsets.get_data()[start - 1]);
1161
268
    size_t num_items =
1162
268
            column_offsets.get_data().back() - column_offsets.get_data()[start - 1]; // -1 is valid
1163
1164
268
    if (num_items > 0) {
1165
209
        auto key_ptr = IColumn::mutate(std::move(column_map.get_keys_ptr()));
1166
209
        auto val_ptr = IColumn::mutate(std::move(column_map.get_values_ptr()));
1167
209
        Defer defer_keys {[&] { column_map.get_keys_ptr() = std::move(key_ptr); }};
1168
209
        Defer defer_values {[&] { column_map.get_values_ptr() = std::move(val_ptr); }};
1169
209
        if (read_offset_only()) {
1170
            // OFFSET_ONLY mode: skip reading actual key/value data, fill with defaults
1171
0
            key_ptr->insert_many_defaults(num_items);
1172
0
            val_ptr->insert_many_defaults(num_items);
1173
209
        } else {
1174
209
            size_t num_read = num_items;
1175
209
            bool key_has_null = false;
1176
209
            bool val_has_null = false;
1177
209
            RETURN_IF_ERROR(_key_iterator->next_batch(&num_read, key_ptr, &key_has_null));
1178
209
            RETURN_IF_ERROR(_val_iterator->next_batch(&num_read, val_ptr, &val_has_null));
1179
209
            DCHECK(num_read == num_items);
1180
209
        }
1181
209
    }
1182
1183
268
    if (is_column_nullable(*dst) && read_meta_columns) {
1184
0
        size_t num_read = *n;
1185
0
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1186
        // in not-null to null linked-schemachange mode,
1187
        // actually we do not change dat data include meta in footer,
1188
        // so may dst from changed meta which is nullable but old data is not nullable,
1189
        // if so, we should set null_map to all null by default
1190
0
        if (_null_iterator) {
1191
0
            bool null_signs_has_null = false;
1192
0
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
1193
0
            RETURN_IF_ERROR(
1194
0
                    _null_iterator->next_batch(&num_read, null_map_column, &null_signs_has_null));
1195
0
        } else {
1196
0
            null_map_ptr->insert_many_vals(0, num_read);
1197
0
        }
1198
0
        DCHECK(num_read == *n);
1199
0
    }
1200
268
    return Status::OK();
1201
268
}
1202
1203
Status MapFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
1204
24
                                             MutableColumnPtr& dst) {
1205
24
    if (!need_to_read()) {
1206
1
        DLOG(INFO) << "Map column iterator column " << _column_name << " skip reading.";
1207
1
        _convert_to_place_holder_column(dst, count);
1208
1
        return Status::OK();
1209
1
    }
1210
1211
23
    _recovery_from_place_holder_column(dst);
1212
1213
23
    if (read_null_map_only()) {
1214
        // NULL_MAP_ONLY mode: read null map by rowids, fill nested ColumnMap with empty defaults
1215
1
        DORIS_CHECK(is_column_nullable(*dst));
1216
1
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
1217
1
        if (_null_iterator) {
1218
1
            auto null_map_ptr = nullable_col.get_null_map_column_ptr();
1219
1
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
1220
1
            RETURN_IF_ERROR(_null_iterator->read_by_rowids(rowids, count, null_map_column));
1221
1
        } else {
1222
            // schema-change: column became nullable but old segment has no null data
1223
0
            auto null_map_ptr = nullable_col.get_null_map_column_ptr();
1224
0
            null_map_ptr->insert_many_vals(0, count);
1225
0
        }
1226
        // fill nested ColumnMap with empty (zero-element) maps
1227
1
        auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
1228
1
                nullable_col.get_nested_column());
1229
1
        column_map.insert_many_defaults(count);
1230
1
        return Status::OK();
1231
1
    }
1232
1233
22
    if (count == 0) {
1234
0
        return Status::OK();
1235
0
    }
1236
1237
    // resolve ColumnMap and nullable wrapper
1238
22
    auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
1239
22
            is_column_nullable(*dst) ? static_cast<ColumnNullable&>(*dst).get_nested_column()
1240
22
                                     : *dst);
1241
22
    const bool read_meta_columns = need_to_read_meta_columns();
1242
22
    MutableColumnPtr offsets_ptr;
1243
22
    if (read_meta_columns) {
1244
22
        offsets_ptr = IColumn::mutate(std::move(column_map.get_offsets_ptr()));
1245
22
    } else {
1246
0
        const auto base_offset =
1247
0
                column_map.get_offsets().empty() ? 0 : column_map.get_offsets().back();
1248
0
        offsets_ptr = ColumnMap::COffsets::create();
1249
0
        assert_cast<ColumnOffset64&, TypeCheckOnRelease::DISABLE>(*offsets_ptr)
1250
0
                .insert_value(base_offset);
1251
0
    }
1252
22
    Defer defer_offsets {[&] {
1253
22
        if (read_meta_columns) {
1254
22
            auto typed_offsets_ptr = ColumnMap::COffsets::cast_to_column_mutptr(
1255
22
                    assert_cast<ColumnMap::COffsets*, TypeCheckOnRelease::DISABLE>(
1256
22
                            offsets_ptr.get()));
1257
22
            offsets_ptr = nullptr;
1258
22
            column_map.get_offsets_ptr() = std::move(typed_offsets_ptr);
1259
22
        }
1260
22
    }};
1261
22
    auto& offsets = static_cast<ColumnArray::ColumnOffsets&>(*offsets_ptr);
1262
22
    size_t base = offsets.get_data().empty() ? 0 : offsets.get_data().back();
1263
1264
    // 1. bulk read null-map if nullable
1265
22
    std::vector<uint8_t> null_mask; // 0: not null, 1: null
1266
22
    if (read_meta_columns) {
1267
22
        if (_map_reader->is_nullable()) {
1268
            // For nullable map columns, the destination column must also be nullable.
1269
0
            if (UNLIKELY(!is_column_nullable(*dst))) {
1270
0
                return Status::InternalError(
1271
0
                        "unexpected non-nullable destination column for nullable map reader");
1272
0
            }
1273
0
            MutableColumnPtr null_map_ptr =
1274
0
                    static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1275
0
            size_t null_before = null_map_ptr->size();
1276
0
            RETURN_IF_ERROR(_null_iterator->read_by_rowids(rowids, count, null_map_ptr));
1277
            // extract a light-weight view to decide element reads
1278
0
            auto& null_map_col = assert_cast<ColumnUInt8&>(*null_map_ptr);
1279
0
            const auto* src = null_map_col.get_data().data() + null_before;
1280
0
            null_mask.assign(src, src + count);
1281
22
        } else if (is_column_nullable(*dst)) {
1282
            // in not-null to null linked-schemachange mode,
1283
            // actually we do not change dat data include meta in footer,
1284
            // so may dst from changed meta which is nullable but old data is not nullable,
1285
            // if so, we should set null_map to all null by default
1286
0
            MutableColumnPtr null_map_ptr =
1287
0
                    static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1288
0
            auto& null_map = assert_cast<ColumnUInt8&>(*null_map_ptr);
1289
0
            null_map.insert_many_vals(0, count);
1290
0
        }
1291
22
    } else if (_map_reader->is_nullable()) {
1292
        // In lazy mode the parent null map has already been materialized during
1293
        // predicate read and filtered together with the block. Reuse that dst
1294
        // null map to avoid re-reading the same meta column from storage.
1295
0
        if (UNLIKELY(!is_column_nullable(*dst))) {
1296
0
            return Status::InternalError(
1297
0
                    "unexpected non-nullable destination column for nullable map reader");
1298
0
        }
1299
0
        const auto& null_map_col = static_cast<const ColumnNullable&>(*dst).get_null_map_column();
1300
0
        DORIS_CHECK(null_map_col.size() == count);
1301
0
        const auto* src = null_map_col.get_data().data();
1302
0
        null_mask.assign(src, src + count);
1303
0
    }
1304
1305
    // 2. Bulk read source start ordinals for requested rows. The offsets stored
1306
    // in dst already describe the filtered output shape when read_meta_columns is
1307
    // false, but they do not contain the source key/value ordinal for each
1308
    // selected rowid. We still need the storage offsets here to seek child
1309
    // iterators to the correct source element ranges.
1310
22
    MutableColumnPtr starts_col = ColumnOffset64::create();
1311
22
    starts_col->reserve(count);
1312
22
    RETURN_IF_ERROR(_offsets_iterator->read_by_rowids(rowids, count, starts_col));
1313
1314
    // 3. bulk read next-start ordinals for rowid+1 (within bounds)
1315
22
    std::vector<rowid_t> next_rowids(count);
1316
3.18k
    for (size_t i = 0; i < count; ++i) {
1317
3.15k
        uint64_t nr = rowids[i] + 1;
1318
3.15k
        next_rowids[i] = nr < _map_reader->num_rows() ? static_cast<rowid_t>(nr)
1319
3.15k
                                                      : static_cast<rowid_t>(0); // placeholder
1320
3.15k
    }
1321
22
    MutableColumnPtr next_starts_col = ColumnOffset64::create();
1322
22
    next_starts_col->reserve(count);
1323
    // read for all; we'll fix out-of-bound cases below
1324
22
    RETURN_IF_ERROR(_offsets_iterator->read_by_rowids(next_rowids.data(), count, next_starts_col));
1325
1326
    // 4. fix next_start for rows whose next_rowid is out-of-bound (rowid == num_rows-1)
1327
3.18k
    for (size_t i = 0; i < count; ++i) {
1328
3.15k
        if (rowids[i] + 1 >= _map_reader->num_rows()) {
1329
            // seek to the last row and consume one to move decoder to end-of-page,
1330
            // then peek page-tail sentinel next_array_item_ordinal as next_start
1331
13
            RETURN_IF_ERROR(_offsets_iterator->seek_to_ordinal(rowids[i]));
1332
13
            size_t one = 1;
1333
13
            bool has_null_unused = false;
1334
13
            MutableColumnPtr tmp = ColumnOffset64::create();
1335
13
            RETURN_IF_ERROR(_offsets_iterator->next_batch(&one, tmp, &has_null_unused));
1336
13
            ordinal_t ns = 0;
1337
13
            RETURN_IF_ERROR(_offsets_iterator->_peek_one_offset(&ns));
1338
            // overwrite with sentinel
1339
13
            assert_cast<ColumnOffset64&, TypeCheckOnRelease::DISABLE>(*next_starts_col)
1340
13
                    .get_data()[i] = ns;
1341
13
        }
1342
3.15k
    }
1343
1344
    // 5. compute sizes and append offsets prefix-sum
1345
22
    auto& starts_data = assert_cast<ColumnOffset64&>(*starts_col).get_data();
1346
22
    auto& next_starts_data = assert_cast<ColumnOffset64&>(*next_starts_col).get_data();
1347
22
    std::vector<size_t> sizes(count, 0);
1348
22
    size_t acc = base;
1349
22
    if (read_meta_columns) {
1350
22
        offsets.get_data().reserve(offsets.get_data().size() + count);
1351
22
    }
1352
3.18k
    for (size_t i = 0; i < count; ++i) {
1353
3.15k
        auto sz = static_cast<size_t>(next_starts_data[i] - starts_data[i]);
1354
3.15k
        if (_map_reader->is_nullable() && !null_mask.empty() && null_mask[i]) {
1355
0
            sz = 0; // null rows do not consume elements
1356
0
        }
1357
3.15k
        sizes[i] = sz;
1358
3.15k
        acc += sz;
1359
3.15k
        if (read_meta_columns) {
1360
3.15k
            offsets.get_data().push_back(acc);
1361
3.15k
        }
1362
3.15k
    }
1363
1364
    // 6. read key/value elements for non-empty sizes
1365
22
    auto keys_ptr = IColumn::mutate(std::move(column_map.get_keys_ptr()));
1366
22
    auto vals_ptr = IColumn::mutate(std::move(column_map.get_values_ptr()));
1367
22
    Defer defer_keys {[&] { column_map.get_keys_ptr() = std::move(keys_ptr); }};
1368
22
    Defer defer_values {[&] { column_map.get_values_ptr() = std::move(vals_ptr); }};
1369
1370
22
    size_t this_run = sizes[0];
1371
22
    auto start_idx = starts_data[0];
1372
22
    auto last_idx = starts_data[0] + this_run;
1373
3.15k
    for (size_t i = 1; i < count; ++i) {
1374
3.13k
        size_t sz = sizes[i];
1375
3.13k
        if (sz == 0) {
1376
1.71k
            continue;
1377
1.71k
        }
1378
1.42k
        auto start = static_cast<ordinal_t>(starts_data[i]);
1379
1.42k
        if (start != last_idx) {
1380
251
            size_t n = this_run;
1381
251
            bool dummy_has_null = false;
1382
1383
251
            if (this_run != 0) {
1384
248
                RETURN_IF_ERROR(_key_iterator->seek_to_ordinal(start_idx));
1385
248
                RETURN_IF_ERROR(_key_iterator->next_batch(&n, keys_ptr, &dummy_has_null));
1386
248
                DCHECK(n == this_run);
1387
1388
248
                n = this_run;
1389
248
                RETURN_IF_ERROR(_val_iterator->seek_to_ordinal(start_idx));
1390
248
                RETURN_IF_ERROR(_val_iterator->next_batch(&n, vals_ptr, &dummy_has_null));
1391
248
                DCHECK(n == this_run);
1392
248
            }
1393
251
            start_idx = start;
1394
251
            this_run = sz;
1395
251
            last_idx = start + sz;
1396
251
            continue;
1397
251
        }
1398
1399
1.17k
        this_run += sz;
1400
1.17k
        last_idx += sz;
1401
1.17k
    }
1402
1403
22
    size_t n = this_run;
1404
22
    bool dummy_has_null = false;
1405
22
    if (this_run != 0) {
1406
7
        RETURN_IF_ERROR(_key_iterator->seek_to_ordinal(start_idx));
1407
7
        RETURN_IF_ERROR(_key_iterator->next_batch(&n, keys_ptr, &dummy_has_null));
1408
7
        DCHECK(n == this_run);
1409
1410
7
        n = this_run;
1411
7
        RETURN_IF_ERROR(_val_iterator->seek_to_ordinal(start_idx));
1412
7
        RETURN_IF_ERROR(_val_iterator->next_batch(&n, vals_ptr, &dummy_has_null));
1413
7
        DCHECK(n == this_run);
1414
7
    }
1415
22
    return Status::OK();
1416
22
}
1417
1418
7
void MapFileColumnIterator::set_lazy_output_requirement() {
1419
7
    set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1420
7
    _key_iterator->set_lazy_output_requirement();
1421
7
    _val_iterator->set_lazy_output_requirement();
1422
7
}
1423
1424
0
void MapFileColumnIterator::remove_pruned_sub_iterators() {
1425
0
    _key_iterator->remove_pruned_sub_iterators();
1426
0
    _val_iterator->remove_pruned_sub_iterators();
1427
0
}
1428
1429
Status MapFileColumnIterator::set_access_paths(const TColumnAccessPaths& all_access_paths,
1430
24
                                               const TColumnAccessPaths& predicate_access_paths) {
1431
24
    if (all_access_paths.empty() && predicate_access_paths.empty()) {
1432
0
        return Status::OK();
1433
0
    }
1434
1435
24
    const auto requirement_before_access_path = _read_requirement;
1436
24
    if (!predicate_access_paths.empty()) {
1437
17
        set_read_requirement_self(ReadRequirement::PREDICATE);
1438
17
        DLOG(INFO) << "Map column iterator set sub-column " << _column_name << " to PREDICATE";
1439
17
    }
1440
1441
24
    const bool has_current_level_data_path =
1442
24
            std::ranges::any_of(all_access_paths, [this](const TColumnAccessPath& path) {
1443
24
                return is_current_level_data_access_path(path, _column_name);
1444
24
            });
1445
24
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
1446
23
    auto sub_predicate_access_paths =
1447
23
            DORIS_TRY(_get_sub_access_paths(predicate_access_paths, true));
1448
23
    if (has_current_level_data_path) {
1449
6
        remove_current_level_meta_access_paths(sub_all_access_paths);
1450
6
    }
1451
23
    const bool has_current_level_predicate_meta_path =
1452
23
            std::ranges::any_of(sub_predicate_access_paths, is_current_level_meta_access_path);
1453
    // Current-level predicate metadata paths are consumed by this map iterator and must not be
1454
    // forwarded to key/value children. The FE keeps all_access_paths as a superset of predicate
1455
    // paths, so meta-only mode is still decided from sub_all_access_paths below.
1456
23
    remove_current_level_meta_access_paths(sub_predicate_access_paths);
1457
1458
23
    if (sub_predicate_access_paths.empty() && _read_requirement == ReadRequirement::PREDICATE &&
1459
23
        !has_current_level_predicate_meta_path) {
1460
        // if no sub-column in predicate_access_paths, but current column is PREDICATE,
1461
        // then we should set key/value iterator to PREDICATE too.
1462
1
        _key_iterator->set_read_requirement(ReadRequirement::PREDICATE);
1463
1
        _val_iterator->set_read_requirement(ReadRequirement::PREDICATE);
1464
1
    }
1465
1466
23
    if (sub_predicate_access_paths.empty()) {
1467
        // Check for meta-only modes (OFFSET_ONLY or NULL_MAP_ONLY). Only skip key/value
1468
        // iterators when no predicate sub-path needs them in the predicate phase.
1469
9
        _check_and_set_meta_read_mode(requirement_before_access_path, sub_all_access_paths);
1470
9
        if (read_offset_only()) {
1471
0
            _key_iterator->set_read_requirement(ReadRequirement::SKIP);
1472
0
            _val_iterator->set_read_requirement(ReadRequirement::SKIP);
1473
0
            DLOG(INFO) << "Map column iterator set column " << _column_name
1474
0
                       << " to OFFSET_ONLY meta read mode, key/value columns set to SKIP";
1475
0
            return Status::OK();
1476
0
        }
1477
9
        if (read_null_map_only()) {
1478
2
            _key_iterator->set_read_requirement(ReadRequirement::SKIP);
1479
2
            _val_iterator->set_read_requirement(ReadRequirement::SKIP);
1480
2
            DLOG(INFO) << "Map column iterator set column " << _column_name
1481
2
                       << " to NULL_MAP_ONLY meta read mode, key/value columns set to SKIP";
1482
2
            return Status::OK();
1483
2
        }
1484
9
    }
1485
1486
    // A current-level data path is consumed by _get_sub_access_paths() and leaves
1487
    // sub_all_access_paths empty after marking key/value as lazy-read targets. Predicate
1488
    // sub-paths still have to be routed to child iterators for the predicate phase.
1489
21
    if (sub_all_access_paths.empty() && sub_predicate_access_paths.empty()) {
1490
2
        return Status::OK();
1491
2
    }
1492
1493
19
    TColumnAccessPaths key_all_access_paths;
1494
19
    TColumnAccessPaths val_all_access_paths;
1495
19
    TColumnAccessPaths key_predicate_access_paths;
1496
19
    TColumnAccessPaths val_predicate_access_paths;
1497
1498
19
    for (auto paths : sub_all_access_paths) {
1499
16
        if (paths.data_access_path.path[0] == ACCESS_ALL) {
1500
            // ACCESS_ALL means element_at(map, key) style access: the key column must be
1501
            // fully read so that the runtime can match the requested key, while any sub-path
1502
            // qualifiers (e.g. OFFSET) apply only to the value column.
1503
            // For key: create a path with just the column name (= full data access).
1504
2
            TColumnAccessPath key_path;
1505
2
            key_path.__set_type(paths.type);
1506
2
            TDataAccessPath key_data_path;
1507
2
            key_data_path.__set_path({_key_iterator->column_name()});
1508
2
            key_path.__set_data_access_path(key_data_path);
1509
2
            key_all_access_paths.emplace_back(std::move(key_path));
1510
            // For value: pass the full sub-path so qualifiers like OFFSET propagate.
1511
2
            paths.data_access_path.path[0] = _val_iterator->column_name();
1512
2
            val_all_access_paths.emplace_back(paths);
1513
14
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_KEYS) {
1514
4
            paths.data_access_path.path[0] = _key_iterator->column_name();
1515
4
            key_all_access_paths.emplace_back(paths);
1516
10
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_VALUES) {
1517
8
            paths.data_access_path.path[0] = _val_iterator->column_name();
1518
8
            val_all_access_paths.emplace_back(paths);
1519
8
        }
1520
16
    }
1521
19
    for (auto paths : sub_predicate_access_paths) {
1522
15
        if (paths.data_access_path.path[0] == ACCESS_ALL) {
1523
            // Same logic as above: key needs full data, value gets the sub-path.
1524
1
            TColumnAccessPath key_path;
1525
1
            key_path.__set_type(paths.type);
1526
1
            TDataAccessPath key_data_path;
1527
1
            key_data_path.__set_path({_key_iterator->column_name()});
1528
1
            key_path.__set_data_access_path(key_data_path);
1529
1
            key_predicate_access_paths.emplace_back(std::move(key_path));
1530
1
            paths.data_access_path.path[0] = _val_iterator->column_name();
1531
1
            val_predicate_access_paths.emplace_back(paths);
1532
14
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_KEYS) {
1533
3
            paths.data_access_path.path[0] = _key_iterator->column_name();
1534
3
            key_predicate_access_paths.emplace_back(paths);
1535
11
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_VALUES) {
1536
11
            paths.data_access_path.path[0] = _val_iterator->column_name();
1537
11
            val_predicate_access_paths.emplace_back(paths);
1538
11
        }
1539
15
    }
1540
1541
19
    const auto need_read_keys =
1542
19
            !key_all_access_paths.empty() || !key_predicate_access_paths.empty();
1543
19
    const auto need_read_values =
1544
19
            !val_all_access_paths.empty() || !val_predicate_access_paths.empty();
1545
1546
19
    if (need_read_keys) {
1547
9
        RETURN_IF_ERROR(
1548
9
                _key_iterator->set_access_paths(key_all_access_paths, key_predicate_access_paths));
1549
        // Apply LAZY_OUTPUT after child predicate paths have been handled. Read requirements are
1550
        // monotonic, so a predicate-only child already promoted to PREDICATE will not
1551
        // be downgraded, while a non-predicate child becomes a lazy materialization target.
1552
9
        _key_iterator->set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1553
10
    } else {
1554
10
        _key_iterator->set_read_requirement(ReadRequirement::SKIP);
1555
10
        DLOG(INFO) << "Map column iterator set key column to SKIP";
1556
10
    }
1557
1558
19
    if (need_read_values) {
1559
15
        RETURN_IF_ERROR(
1560
15
                _val_iterator->set_access_paths(val_all_access_paths, val_predicate_access_paths));
1561
        // Same as keys: predicate-only value paths stay PREDICATE because this
1562
        // post-processing update cannot lower a stronger child requirement.
1563
15
        _val_iterator->set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1564
15
    } else {
1565
4
        _val_iterator->set_read_requirement(ReadRequirement::SKIP);
1566
4
        DLOG(INFO) << "Map column iterator set value column to SKIP";
1567
4
    }
1568
19
    return Status::OK();
1569
19
}
1570
1571
12
void MapFileColumnIterator::set_read_phase(ReadPhase mode) {
1572
12
    ColumnIterator::set_read_phase(mode);
1573
12
    _key_iterator->set_read_phase(mode);
1574
12
    _val_iterator->set_read_phase(mode);
1575
12
}
1576
1577
0
void MapFileColumnIterator::finalize_lazy_phase(MutableColumnPtr& dst) {
1578
0
    _recovery_from_place_holder_column(dst);
1579
0
    auto& map_column = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
1580
0
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
1581
0
    auto keys_ptr = IColumn::mutate(std::move(map_column.get_keys_ptr()));
1582
0
    auto vals_ptr = IColumn::mutate(std::move(map_column.get_values_ptr()));
1583
0
    _key_iterator->finalize_lazy_phase(keys_ptr);
1584
0
    _val_iterator->finalize_lazy_phase(vals_ptr);
1585
0
    map_column.get_keys_ptr() = std::move(keys_ptr);
1586
0
    map_column.get_values_ptr() = std::move(vals_ptr);
1587
0
}
1588
1589
7
void MapFileColumnIterator::set_read_requirement(ReadRequirement requirement) {
1590
7
    set_read_requirement_self(requirement);
1591
7
    _key_iterator->set_read_requirement(requirement);
1592
7
    _val_iterator->set_read_requirement(requirement);
1593
7
}
1594
1595
18
bool MapFileColumnIterator::has_lazy_read_target() const {
1596
18
    return _read_requirement == ReadRequirement::LAZY_OUTPUT ||
1597
18
           _key_iterator->has_lazy_read_target() || _val_iterator->has_lazy_read_target();
1598
18
}
1599
1600
////////////////////////////////////////////////////////////////////////////////
1601
1602
StructFileColumnIterator::StructFileColumnIterator(
1603
        std::shared_ptr<ColumnReader> reader, ColumnIteratorUPtr null_iterator,
1604
        std::vector<ColumnIteratorUPtr>&& sub_column_iterators)
1605
58
        : _struct_reader(reader), _sub_column_iterators(std::move(sub_column_iterators)) {
1606
58
    if (_struct_reader->is_nullable()) {
1607
2
        _null_iterator = std::move(null_iterator);
1608
2
    }
1609
58
}
1610
1611
0
Status StructFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1612
0
    if (_read_requirement == ReadRequirement::SKIP) {
1613
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1614
0
        return Status::OK();
1615
0
    }
1616
1617
0
    for (auto& column_iterator : _sub_column_iterators) {
1618
0
        RETURN_IF_ERROR(column_iterator->init(opts));
1619
0
    }
1620
0
    if (_struct_reader->is_nullable()) {
1621
0
        RETURN_IF_ERROR(_null_iterator->init(opts));
1622
0
    }
1623
0
    return Status::OK();
1624
0
}
1625
1626
4
Status StructFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1627
4
    if (!need_to_read()) {
1628
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1629
0
        _convert_to_place_holder_column(dst, *n);
1630
0
        return Status::OK();
1631
0
    }
1632
1633
4
    _recovery_from_place_holder_column(dst);
1634
1635
4
    if (read_null_map_only()) {
1636
        // NULL_MAP_ONLY mode: read null map, fill nested ColumnStruct with empty defaults
1637
1
        DORIS_CHECK(is_column_nullable(*dst));
1638
1
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
1639
1
        auto null_map_ptr = nullable_col.get_null_map_column_ptr();
1640
1
        size_t num_read = *n;
1641
1
        if (_null_iterator) {
1642
1
            bool null_signs_has_null = false;
1643
1
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
1644
1
            RETURN_IF_ERROR(
1645
1
                    _null_iterator->next_batch(&num_read, null_map_column, &null_signs_has_null));
1646
1
        } else {
1647
            // schema-change: column became nullable but old segment has no null data
1648
0
            null_map_ptr->insert_many_vals(0, num_read);
1649
0
        }
1650
1
        DCHECK(num_read == *n);
1651
        // fill nested ColumnStruct with defaults to maintain consistent column sizes
1652
1
        auto& column_struct = assert_cast<ColumnStruct&, TypeCheckOnRelease::DISABLE>(
1653
1
                nullable_col.get_nested_column());
1654
1
        column_struct.insert_many_defaults(num_read);
1655
1
        *has_null = true;
1656
1
        return Status::OK();
1657
1
    }
1658
1659
3
    auto& column_struct = assert_cast<ColumnStruct&, TypeCheckOnRelease::DISABLE>(
1660
3
            is_column_nullable(*dst) ? static_cast<ColumnNullable&>(*dst).get_nested_column()
1661
3
                                     : *dst);
1662
9
    for (size_t i = 0; i < column_struct.tuple_size(); i++) {
1663
6
        size_t num_read = *n;
1664
6
        auto sub_column_ptr = IColumn::mutate(std::move(column_struct.get_column_ptr(i)));
1665
6
        Defer defer_sub_column {
1666
6
                [&] { column_struct.get_column_ptr(i) = std::move(sub_column_ptr); }};
1667
6
        bool column_has_null = false;
1668
6
        RETURN_IF_ERROR(
1669
6
                _sub_column_iterators[i]->next_batch(&num_read, sub_column_ptr, &column_has_null));
1670
6
        DCHECK(num_read == *n);
1671
6
    }
1672
1673
3
    if (is_column_nullable(*dst) && need_to_read_meta_columns()) {
1674
0
        size_t num_read = *n;
1675
0
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1676
        // in not-null to null linked-schemachange mode,
1677
        // actually we do not change dat data include meta in footer,
1678
        // so may dst from changed meta which is nullable but old data is not nullable,
1679
        // if so, we should set null_map to all null by default
1680
0
        if (_null_iterator) {
1681
0
            bool null_signs_has_null = false;
1682
0
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
1683
0
            RETURN_IF_ERROR(
1684
0
                    _null_iterator->next_batch(&num_read, null_map_column, &null_signs_has_null));
1685
0
        } else {
1686
0
            null_map_ptr->insert_many_vals(0, num_read);
1687
0
        }
1688
0
        DCHECK(num_read == *n);
1689
0
    }
1690
1691
3
    return Status::OK();
1692
3
}
1693
1694
2
Status StructFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
1695
2
    if (!need_to_read()) {
1696
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1697
0
        return Status::OK();
1698
0
    }
1699
1700
2
    if (read_null_map_only()) {
1701
        // In NULL_MAP_ONLY mode, only seek the null iterator; skip all sub-column iterators
1702
0
        if (_struct_reader->is_nullable() && _null_iterator) {
1703
0
            RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1704
0
        }
1705
0
        return Status::OK();
1706
0
    }
1707
1708
4
    for (auto& column_iterator : _sub_column_iterators) {
1709
4
        RETURN_IF_ERROR(column_iterator->seek_to_ordinal(ord));
1710
4
    }
1711
1712
2
    if (_struct_reader->is_nullable() && need_to_read_meta_columns()) {
1713
0
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1714
0
    }
1715
2
    return Status::OK();
1716
2
}
1717
1718
0
Status StructFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
1719
0
    for (auto& column_iterator : _sub_column_iterators) {
1720
0
        RETURN_IF_ERROR(column_iterator->init_prefetcher(params));
1721
0
    }
1722
0
    if (_struct_reader->is_nullable()) {
1723
0
        RETURN_IF_ERROR(_null_iterator->init_prefetcher(params));
1724
0
    }
1725
0
    return Status::OK();
1726
0
}
1727
1728
void StructFileColumnIterator::collect_prefetchers(
1729
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
1730
2
        PrefetcherInitMethod init_method) {
1731
2
    if (!need_to_read()) {
1732
0
        return;
1733
0
    }
1734
2
    if (_struct_reader->is_nullable()) {
1735
2
        _null_iterator->collect_prefetchers(prefetchers, init_method);
1736
2
    }
1737
2
    if (read_null_map_only()) {
1738
0
        return;
1739
0
    }
1740
4
    for (auto& column_iterator : _sub_column_iterators) {
1741
4
        if (column_iterator->need_to_read()) {
1742
2
            column_iterator->collect_prefetchers(prefetchers, init_method);
1743
2
        }
1744
4
    }
1745
2
}
1746
1747
Status StructFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
1748
1
                                                MutableColumnPtr& dst) {
1749
1
    if (!need_to_read()) {
1750
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1751
0
        _convert_to_place_holder_column(dst, count);
1752
0
        return Status::OK();
1753
0
    }
1754
1755
1
    _recovery_from_place_holder_column(dst);
1756
1757
1
    if (count == 0) {
1758
0
        return Status::OK();
1759
0
    }
1760
1761
1
    size_t this_run = 1;
1762
1
    auto start_idx = rowids[0];
1763
1
    auto last_idx = rowids[0];
1764
5
    for (size_t i = 1; i < count; ++i) {
1765
4
        if (last_idx == rowids[i] - 1) {
1766
3
            last_idx = rowids[i];
1767
3
            this_run++;
1768
3
            continue;
1769
3
        }
1770
1
        RETURN_IF_ERROR(seek_to_ordinal(start_idx));
1771
1
        size_t num_read = this_run;
1772
1
        RETURN_IF_ERROR(next_batch(&num_read, dst));
1773
1
        DCHECK_EQ(num_read, this_run);
1774
1775
1
        start_idx = rowids[i];
1776
1
        last_idx = rowids[i];
1777
1
        this_run = 1;
1778
1
    }
1779
1780
1
    RETURN_IF_ERROR(seek_to_ordinal(start_idx));
1781
1
    size_t num_read = this_run;
1782
1
    RETURN_IF_ERROR(next_batch(&num_read, dst));
1783
1
    DCHECK_EQ(num_read, this_run);
1784
1
    return Status::OK();
1785
1
}
1786
1787
12
void StructFileColumnIterator::set_lazy_output_requirement() {
1788
12
    set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1789
24
    for (auto& sub_iterator : _sub_column_iterators) {
1790
24
        sub_iterator->set_lazy_output_requirement();
1791
24
    }
1792
12
}
1793
1794
4
void StructFileColumnIterator::remove_pruned_sub_iterators() {
1795
13
    for (auto it = _sub_column_iterators.begin(); it != _sub_column_iterators.end();) {
1796
9
        auto& sub_iterator = *it;
1797
9
        if (sub_iterator->read_requirement() == ReadRequirement::SKIP) {
1798
4
            DLOG(INFO) << "Struct column iterator remove pruned sub-column "
1799
4
                       << sub_iterator->column_name();
1800
4
            it = _sub_column_iterators.erase(it);
1801
5
        } else {
1802
5
            sub_iterator->remove_pruned_sub_iterators();
1803
5
            ++it;
1804
5
        }
1805
9
    }
1806
4
}
1807
1808
Status StructFileColumnIterator::set_access_paths(
1809
        const TColumnAccessPaths& all_access_paths,
1810
43
        const TColumnAccessPaths& predicate_access_paths) {
1811
43
    if (all_access_paths.empty() && predicate_access_paths.empty()) {
1812
1
        return Status::OK();
1813
1
    }
1814
1815
42
    const auto requirement_before_access_path = _read_requirement;
1816
42
    if (!predicate_access_paths.empty()) {
1817
31
        set_read_requirement_self(ReadRequirement::PREDICATE);
1818
31
        DLOG(INFO) << "Struct column iterator set sub-column " << _column_name << " to PREDICATE";
1819
31
    }
1820
1821
42
    const bool has_current_level_data_path =
1822
42
            std::ranges::any_of(all_access_paths, [this](const TColumnAccessPath& path) {
1823
36
                return is_current_level_data_access_path(path, _column_name);
1824
36
            });
1825
42
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
1826
38
    auto sub_predicate_access_paths =
1827
38
            DORIS_TRY(_get_sub_access_paths(predicate_access_paths, true));
1828
38
    if (has_current_level_data_path) {
1829
7
        remove_current_level_meta_access_paths(sub_all_access_paths);
1830
7
    }
1831
38
    const bool has_current_level_predicate_meta_path =
1832
38
            std::ranges::any_of(sub_predicate_access_paths, is_current_level_meta_access_path);
1833
    // Current-level predicate metadata paths are consumed by this struct iterator and must not be
1834
    // forwarded to child fields. The FE keeps all_access_paths as a superset of predicate paths, so
1835
    // NULL_MAP_ONLY is still decided from sub_all_access_paths below.
1836
38
    remove_current_level_meta_access_paths(sub_predicate_access_paths);
1837
1838
38
    if (sub_predicate_access_paths.empty()) {
1839
        // Check for NULL_MAP_ONLY mode: only read null map, skip all sub-columns.
1840
        // Do not take this early return when predicate child paths must still be read.
1841
15
        _check_and_set_meta_read_mode(requirement_before_access_path, sub_all_access_paths);
1842
15
        if (read_null_map_only()) {
1843
3
            for (auto& sub_iterator : _sub_column_iterators) {
1844
3
                sub_iterator->set_read_requirement(ReadRequirement::SKIP);
1845
3
            }
1846
2
            DLOG(INFO) << "Struct column iterator set column " << _column_name
1847
2
                       << " to NULL_MAP_ONLY meta read mode, all sub-columns set to SKIP";
1848
2
            return Status::OK();
1849
2
        }
1850
15
    }
1851
1852
36
    const auto no_sub_column_to_skip = sub_all_access_paths.empty();
1853
36
    const auto no_predicate_sub_column = sub_predicate_access_paths.empty();
1854
1855
72
    for (auto& sub_iterator : _sub_column_iterators) {
1856
72
        const auto name = sub_iterator->column_name();
1857
72
        TColumnAccessPaths sub_all_access_paths_of_this;
1858
72
        if (!no_sub_column_to_skip) {
1859
48
            for (const auto& paths : sub_all_access_paths) {
1860
48
                if (paths.data_access_path.path[0] == name) {
1861
24
                    sub_all_access_paths_of_this.emplace_back(paths);
1862
24
                }
1863
48
            }
1864
48
        }
1865
1866
72
        TColumnAccessPaths sub_predicate_access_paths_of_this;
1867
72
        if (!no_predicate_sub_column) {
1868
46
            for (const auto& paths : sub_predicate_access_paths) {
1869
46
                if (StringCaseEqual()(paths.data_access_path.path[0], name)) {
1870
23
                    sub_predicate_access_paths_of_this.emplace_back(paths);
1871
23
                }
1872
46
            }
1873
46
        }
1874
1875
        // Predicate-only child paths still need to be routed to the child iterator
1876
        // even when the child is not requested by ordinary projection access paths.
1877
72
        const bool need_to_read = no_sub_column_to_skip || !sub_all_access_paths_of_this.empty() ||
1878
72
                                  !sub_predicate_access_paths_of_this.empty();
1879
72
        if (!need_to_read) {
1880
23
            set_read_requirement_self(ReadRequirement::SKIP);
1881
23
            sub_iterator->set_read_requirement(ReadRequirement::SKIP);
1882
23
            DLOG(INFO) << "Struct column iterator set sub-column " << name << " to SKIP";
1883
23
            continue;
1884
23
        }
1885
1886
49
        if (no_predicate_sub_column && _read_requirement == ReadRequirement::PREDICATE &&
1887
49
            !has_current_level_predicate_meta_path) {
1888
            // if no sub-column in predicate_access_paths, but current column is PREDICATE,
1889
            // then we should set sub iterator to PREDICATE too.
1890
6
            sub_iterator->set_read_requirement(ReadRequirement::PREDICATE);
1891
6
        }
1892
1893
49
        RETURN_IF_ERROR(sub_iterator->set_access_paths(sub_all_access_paths_of_this,
1894
49
                                                       sub_predicate_access_paths_of_this));
1895
        // Set LAZY_OUTPUT after routing child predicate paths. If the child was needed only for
1896
        // predicate evaluation, set_access_paths() has already promoted it to
1897
        // PREDICATE and this monotonic update will not downgrade it. Otherwise, this
1898
        // marks the child as a lazy materialization target.
1899
48
        set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1900
48
        sub_iterator->set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1901
48
    }
1902
35
    return Status::OK();
1903
36
}
1904
1905
24
void StructFileColumnIterator::set_read_phase(ReadPhase mode) {
1906
24
    ColumnIterator::set_read_phase(mode);
1907
46
    for (auto& sub_iterator : _sub_column_iterators) {
1908
46
        sub_iterator->set_read_phase(mode);
1909
46
    }
1910
24
}
1911
1912
1
void StructFileColumnIterator::finalize_lazy_phase(MutableColumnPtr& dst) {
1913
1
    _recovery_from_place_holder_column(dst);
1914
1
    auto& column_struct = assert_cast<ColumnStruct&, TypeCheckOnRelease::DISABLE>(
1915
1
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
1916
1917
2
    for (size_t i = 0; i < _sub_column_iterators.size(); ++i) {
1918
1
        auto& sub_column = column_struct.get_column_ptr(i);
1919
1
        MutableColumnPtr mutable_sub_column = IColumn::mutate(std::move(sub_column));
1920
1
        _sub_column_iterators[i]->finalize_lazy_phase(mutable_sub_column);
1921
1
        sub_column = std::move(mutable_sub_column);
1922
1
    }
1923
1
}
1924
1925
10
void StructFileColumnIterator::set_read_requirement(ReadRequirement requirement) {
1926
10
    set_read_requirement_self(requirement);
1927
20
    for (const auto& sub_column_iterator : _sub_column_iterators) {
1928
20
        sub_column_iterator->set_read_requirement(requirement);
1929
20
    }
1930
10
}
1931
1932
29
bool StructFileColumnIterator::has_lazy_read_target() const {
1933
29
    if (_read_requirement == ReadRequirement::LAZY_OUTPUT) {
1934
2
        return true;
1935
2
    }
1936
27
    return std::any_of(_sub_column_iterators.begin(), _sub_column_iterators.end(),
1937
52
                       [](const auto& sub_column_iterator) {
1938
52
                           return sub_column_iterator->has_lazy_read_target();
1939
52
                       });
1940
29
}
1941
1942
////////////////////////////////////////////////////////////////////////////////
1943
311
Status OffsetFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1944
311
    RETURN_IF_ERROR(_offset_iterator->init(opts));
1945
    // allocate peek tmp column once
1946
311
    _peek_tmp_col = ColumnOffset64::create();
1947
311
    return Status::OK();
1948
311
}
1949
1950
310
Status OffsetFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1951
310
    RETURN_IF_ERROR(_offset_iterator->next_batch(n, dst, has_null));
1952
310
    return Status::OK();
1953
310
}
1954
1955
612
Status OffsetFileColumnIterator::_peek_one_offset(ordinal_t* offset) {
1956
612
    if (_offset_iterator->get_current_page()->has_remaining()) {
1957
305
        PageDecoder* offset_page_decoder = _offset_iterator->get_current_page()->data_decoder.get();
1958
305
        size_t n = 1;
1959
305
        _peek_tmp_col->clear();
1960
305
        RETURN_IF_ERROR(offset_page_decoder->peek_next_batch(&n, _peek_tmp_col)); // not null
1961
305
        DCHECK(_peek_tmp_col->size() == 1);
1962
305
        *offset =
1963
305
                assert_cast<const ColumnOffset64*, TypeCheckOnRelease::DISABLE>(_peek_tmp_col.get())
1964
305
                        ->get_element(0);
1965
307
    } else {
1966
307
        *offset = _offset_iterator->get_current_page()->next_array_item_ordinal;
1967
307
    }
1968
612
    return Status::OK();
1969
612
}
1970
1971
0
Status OffsetFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
1972
0
    return _offset_iterator->init_prefetcher(params);
1973
0
}
1974
1975
void OffsetFileColumnIterator::collect_prefetchers(
1976
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
1977
2
        PrefetcherInitMethod init_method) {
1978
2
    _offset_iterator->collect_prefetchers(prefetchers, init_method);
1979
2
}
1980
1981
/**
1982
 *  first_storage_offset read from page should smaller than next_storage_offset which here call _peek_one_offset from page,
1983
    and first_column_offset is keep in memory data which is different dimension with (first_storage_offset and next_storage_offset)
1984
     eg. step1. read page: first_storage_offset = 16382
1985
         step2. read page below with _peek_one_offset(&last_offset): last_offset = 16387
1986
         step3. first_offset = 126 which is calculate in column offsets
1987
         for loop column offsets element in size
1988
            we can calculate from first_storage_offset to next_storage_offset one by one to fill with offsets_data in memory column offsets
1989
 * @param start
1990
 * @param column_offsets
1991
 * @return
1992
 */
1993
Status OffsetFileColumnIterator::_calculate_offsets(ssize_t start,
1994
298
                                                    ColumnArray::ColumnOffsets& column_offsets) {
1995
298
    ordinal_t next_storage_offset = 0;
1996
298
    RETURN_IF_ERROR(_peek_one_offset(&next_storage_offset));
1997
1998
    // calculate real offsets
1999
298
    auto& offsets_data = column_offsets.get_data();
2000
298
    ordinal_t first_column_offset = offsets_data[start - 1]; // -1 is valid
2001
298
    ordinal_t first_storage_offset = offsets_data[start];
2002
298
    DCHECK(next_storage_offset >= first_storage_offset);
2003
98.1k
    for (ssize_t i = start; i < offsets_data.size() - 1; ++i) {
2004
97.8k
        offsets_data[i] = first_column_offset + (offsets_data[i + 1] - first_storage_offset);
2005
97.8k
    }
2006
    // last offset
2007
298
    offsets_data[offsets_data.size() - 1] =
2008
298
            first_column_offset + (next_storage_offset - first_storage_offset);
2009
298
    return Status::OK();
2010
298
}
2011
2012
////////////////////////////////////////////////////////////////////////////////
2013
ArrayFileColumnIterator::ArrayFileColumnIterator(std::shared_ptr<ColumnReader> reader,
2014
                                                 OffsetFileColumnIteratorUPtr offset_reader,
2015
                                                 ColumnIteratorUPtr item_iterator,
2016
                                                 ColumnIteratorUPtr null_iterator)
2017
60
        : _array_reader(reader),
2018
60
          _offset_iterator(std::move(offset_reader)),
2019
60
          _item_iterator(std::move(item_iterator)) {
2020
60
    if (_array_reader->is_nullable()) {
2021
30
        _null_iterator = std::move(null_iterator);
2022
30
    }
2023
60
}
2024
2025
30
Status ArrayFileColumnIterator::init(const ColumnIteratorOptions& opts) {
2026
30
    if (_read_requirement == ReadRequirement::SKIP) {
2027
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
2028
0
        return Status::OK();
2029
0
    }
2030
2031
30
    RETURN_IF_ERROR(_offset_iterator->init(opts));
2032
30
    RETURN_IF_ERROR(_item_iterator->init(opts));
2033
30
    if (_array_reader->is_nullable()) {
2034
28
        RETURN_IF_ERROR(_null_iterator->init(opts));
2035
28
    }
2036
30
    return Status::OK();
2037
30
}
2038
2039
31
Status ArrayFileColumnIterator::_seek_by_offsets(ordinal_t ord) {
2040
31
    if (read_offset_only()) {
2041
        // In OFFSET_ONLY mode, item iterator is SKIP, no need to seek it
2042
0
        return Status::OK();
2043
0
    }
2044
    // using offsets info
2045
31
    ordinal_t offset = 0;
2046
31
    RETURN_IF_ERROR(_offset_iterator->_peek_one_offset(&offset));
2047
31
    RETURN_IF_ERROR(_item_iterator->seek_to_ordinal(offset));
2048
31
    return Status::OK();
2049
31
}
2050
2051
33
Status ArrayFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
2052
33
    if (!need_to_read()) {
2053
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
2054
0
        return Status::OK();
2055
0
    }
2056
2057
33
    if (read_null_map_only()) {
2058
        // In NULL_MAP_ONLY mode, only seek the null iterator; skip offset and item iterators
2059
2
        if (_array_reader->is_nullable() && _null_iterator) {
2060
2
            RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
2061
2
        }
2062
2
        return Status::OK();
2063
2
    }
2064
2065
31
    RETURN_IF_ERROR(_offset_iterator->seek_to_ordinal(ord));
2066
31
    if (_array_reader->is_nullable()) {
2067
29
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
2068
29
    }
2069
31
    return _seek_by_offsets(ord);
2070
31
}
2071
2072
32
Status ArrayFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
2073
32
    if (!need_to_read()) {
2074
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading, read phase"
2075
0
                   << static_cast<int>(_read_phase)
2076
0
                   << ", read requirement: " << static_cast<int>(_read_requirement);
2077
0
        _convert_to_place_holder_column(dst, *n);
2078
0
        return Status::OK();
2079
0
    }
2080
2081
32
    _recovery_from_place_holder_column(dst);
2082
2083
32
    if (read_null_map_only()) {
2084
        // NULL_MAP_ONLY mode: read null map, fill nested ColumnArray with empty defaults
2085
3
        DORIS_CHECK(is_column_nullable(*dst));
2086
3
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
2087
3
        auto null_map_ptr = nullable_col.get_null_map_column_ptr();
2088
3
        size_t num_read = *n;
2089
3
        if (_null_iterator) {
2090
3
            bool null_signs_has_null = false;
2091
3
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
2092
3
            RETURN_IF_ERROR(
2093
3
                    _null_iterator->next_batch(&num_read, null_map_column, &null_signs_has_null));
2094
3
        } else {
2095
            // schema-change: column became nullable but old segment has no null data
2096
0
            null_map_ptr->insert_many_vals(0, num_read);
2097
0
        }
2098
3
        DCHECK(num_read == *n);
2099
        // fill nested ColumnArray with empty (zero-length) arrays
2100
3
        auto& column_array = assert_cast<ColumnArray&, TypeCheckOnRelease::DISABLE>(
2101
3
                nullable_col.get_nested_column());
2102
3
        column_array.insert_many_defaults(num_read);
2103
3
        *has_null = true;
2104
3
        return Status::OK();
2105
3
    }
2106
2107
29
    auto& column_array = assert_cast<ColumnArray&, TypeCheckOnRelease::DISABLE>(
2108
29
            is_column_nullable(*dst) ? static_cast<ColumnNullable&>(*dst).get_nested_column()
2109
29
                                     : *dst);
2110
2111
29
    bool offsets_has_null = false;
2112
29
    const bool read_meta_columns = need_to_read_meta_columns();
2113
29
    MutableColumnPtr column_offsets_ptr;
2114
29
    if (read_meta_columns) {
2115
29
        column_offsets_ptr = IColumn::mutate(std::move(column_array.get_offsets_ptr()));
2116
29
    } else {
2117
0
        const auto base_offset =
2118
0
                column_array.get_offsets().empty() ? 0 : column_array.get_offsets().back();
2119
0
        column_offsets_ptr = ColumnArray::ColumnOffsets::create();
2120
0
        assert_cast<ColumnOffset64&, TypeCheckOnRelease::DISABLE>(*column_offsets_ptr)
2121
0
                .insert_value(base_offset);
2122
0
    }
2123
29
    Defer defer_offsets {[&] {
2124
29
        if (read_meta_columns) {
2125
29
            auto typed_column_offsets_ptr = ColumnArray::ColumnOffsets::cast_to_column_mutptr(
2126
29
                    assert_cast<ColumnArray::ColumnOffsets*, TypeCheckOnRelease::DISABLE>(
2127
29
                            column_offsets_ptr.get()));
2128
29
            column_offsets_ptr = nullptr;
2129
29
            column_array.get_offsets_ptr() = std::move(typed_column_offsets_ptr);
2130
29
        }
2131
29
    }};
2132
29
    ssize_t start = column_offsets_ptr->size();
2133
29
    RETURN_IF_ERROR(_offset_iterator->next_batch(n, column_offsets_ptr, &offsets_has_null));
2134
29
    if (*n == 0) {
2135
0
        return Status::OK();
2136
0
    }
2137
29
    auto& column_offsets = static_cast<ColumnArray::ColumnOffsets&>(*column_offsets_ptr);
2138
29
    RETURN_IF_ERROR(_offset_iterator->_calculate_offsets(start, column_offsets));
2139
29
    size_t num_items =
2140
29
            column_offsets.get_data().back() - column_offsets.get_data()[start - 1]; // -1 is valid
2141
29
    if (num_items > 0) {
2142
27
        auto column_items_ptr = IColumn::mutate(std::move(column_array.get_data_ptr()));
2143
27
        Defer defer_items {[&] { column_array.get_data_ptr() = std::move(column_items_ptr); }};
2144
27
        if (read_offset_only()) {
2145
            // OFFSET_ONLY mode: skip reading actual item data, fill with defaults
2146
0
            column_items_ptr->insert_many_defaults(num_items);
2147
27
        } else {
2148
27
            size_t num_read = num_items;
2149
27
            bool items_has_null = false;
2150
27
            RETURN_IF_ERROR(
2151
27
                    _item_iterator->next_batch(&num_read, column_items_ptr, &items_has_null));
2152
27
            DCHECK(num_read == num_items);
2153
27
        }
2154
27
    }
2155
2156
29
    if (is_column_nullable(*dst) && read_meta_columns) {
2157
27
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
2158
27
        size_t num_read = *n;
2159
        // in not-null to null linked-schemachange mode,
2160
        // actually we do not change dat data include meta in footer,
2161
        // so may dst from changed meta which is nullable but old data is not nullable,
2162
        // if so, we should set null_map to all null by default
2163
27
        if (_null_iterator) {
2164
27
            bool null_signs_has_null = false;
2165
27
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
2166
27
            RETURN_IF_ERROR(
2167
27
                    _null_iterator->next_batch(&num_read, null_map_column, &null_signs_has_null));
2168
27
        } else {
2169
0
            null_map_ptr->insert_many_vals(0, num_read);
2170
0
        }
2171
27
        DCHECK(num_read == *n);
2172
27
    }
2173
2174
29
    return Status::OK();
2175
29
}
2176
2177
0
Status ArrayFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
2178
0
    RETURN_IF_ERROR(_offset_iterator->init_prefetcher(params));
2179
0
    RETURN_IF_ERROR(_item_iterator->init_prefetcher(params));
2180
0
    if (_array_reader->is_nullable()) {
2181
0
        RETURN_IF_ERROR(_null_iterator->init_prefetcher(params));
2182
0
    }
2183
0
    return Status::OK();
2184
0
}
2185
2186
void ArrayFileColumnIterator::collect_prefetchers(
2187
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
2188
1
        PrefetcherInitMethod init_method) {
2189
1
    if (!need_to_read()) {
2190
0
        return;
2191
0
    }
2192
1
    if (!read_null_map_only()) {
2193
1
        _offset_iterator->collect_prefetchers(prefetchers, init_method);
2194
1
    }
2195
1
    if (_array_reader->is_nullable()) {
2196
1
        _null_iterator->collect_prefetchers(prefetchers, init_method);
2197
1
    }
2198
1
    if (read_offset_only() || read_null_map_only()) {
2199
0
        return;
2200
0
    }
2201
    // the actual data pages to read of item column depends on the read result of offset column,
2202
    // so we can't init prefetch blocks according to rowids, just prefetch all data blocks here.
2203
1
    if (_item_iterator->need_to_read()) {
2204
1
        _item_iterator->collect_prefetchers(prefetchers, PrefetcherInitMethod::ALL_DATA_BLOCKS);
2205
1
    }
2206
1
}
2207
2208
Status ArrayFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
2209
12
                                               MutableColumnPtr& dst) {
2210
12
    if (!need_to_read()) {
2211
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
2212
0
        _convert_to_place_holder_column(dst, count);
2213
0
        return Status::OK();
2214
0
    }
2215
2216
12
    _recovery_from_place_holder_column(dst);
2217
2218
26
    for (size_t i = 0; i < count; ++i) {
2219
        // TODO(cambyszju): now read array one by one, need optimize later
2220
14
        RETURN_IF_ERROR(seek_to_ordinal(rowids[i]));
2221
14
        size_t num_read = 1;
2222
14
        RETURN_IF_ERROR(next_batch(&num_read, dst));
2223
14
    }
2224
12
    return Status::OK();
2225
12
}
2226
2227
3
void ArrayFileColumnIterator::set_lazy_output_requirement() {
2228
3
    set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
2229
3
    _item_iterator->set_lazy_output_requirement();
2230
3
}
2231
2232
1
void ArrayFileColumnIterator::remove_pruned_sub_iterators() {
2233
1
    _item_iterator->remove_pruned_sub_iterators();
2234
1
}
2235
2236
92
void ArrayFileColumnIterator::set_read_phase(ReadPhase mode) {
2237
92
    ColumnIterator::set_read_phase(mode);
2238
92
    _item_iterator->set_read_phase(mode);
2239
92
}
2240
2241
0
void ArrayFileColumnIterator::finalize_lazy_phase(MutableColumnPtr& dst) {
2242
0
    _recovery_from_place_holder_column(dst);
2243
0
    auto& column_array = assert_cast<ColumnArray&, TypeCheckOnRelease::DISABLE>(
2244
0
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
2245
0
    auto item_column_ptr = IColumn::mutate(std::move(column_array.get_data_ptr()));
2246
0
    _item_iterator->finalize_lazy_phase(item_column_ptr);
2247
0
    column_array.get_data_ptr() = std::move(item_column_ptr);
2248
0
}
2249
2250
5
void ArrayFileColumnIterator::set_read_requirement(ReadRequirement requirement) {
2251
5
    set_read_requirement_self(requirement);
2252
5
    _item_iterator->set_read_requirement(requirement);
2253
5
}
2254
2255
14
bool ArrayFileColumnIterator::has_lazy_read_target() const {
2256
14
    return _read_requirement == ReadRequirement::LAZY_OUTPUT ||
2257
14
           _item_iterator->has_lazy_read_target();
2258
14
}
2259
2260
Status ArrayFileColumnIterator::set_access_paths(const TColumnAccessPaths& all_access_paths,
2261
22
                                                 const TColumnAccessPaths& predicate_access_paths) {
2262
22
    if (all_access_paths.empty() && predicate_access_paths.empty()) {
2263
0
        return Status::OK();
2264
0
    }
2265
2266
22
    const auto requirement_before_access_path = _read_requirement;
2267
22
    if (!predicate_access_paths.empty()) {
2268
16
        set_read_requirement_self(ReadRequirement::PREDICATE);
2269
16
        DLOG(INFO) << "Array column iterator set sub-column " << _column_name << " to PREDICATE";
2270
16
    }
2271
2272
22
    const bool has_current_level_data_path =
2273
22
            std::ranges::any_of(all_access_paths, [this](const TColumnAccessPath& path) {
2274
22
                return is_current_level_data_access_path(path, _column_name);
2275
22
            });
2276
22
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
2277
22
    auto sub_predicate_access_paths =
2278
22
            DORIS_TRY(_get_sub_access_paths(predicate_access_paths, true));
2279
22
    if (has_current_level_data_path) {
2280
        // A current-level data path already reads the array offsets while materializing the array.
2281
        // Do not let a redundant current-level OFFSET/NULL path switch this iterator into a
2282
        // meta-only mode that would skip item data.
2283
3
        remove_current_level_meta_access_paths(sub_all_access_paths);
2284
3
    }
2285
22
    const bool has_current_level_predicate_meta_path =
2286
22
            std::ranges::any_of(sub_predicate_access_paths, is_current_level_meta_access_path);
2287
    // Current-level predicate metadata paths are consumed by this array iterator and must not be
2288
    // forwarded to the item iterator. The FE keeps all_access_paths as a superset of predicate
2289
    // paths, so meta-only mode is still decided from sub_all_access_paths below.
2290
22
    auto removed =
2291
22
            std::ranges::remove_if(sub_predicate_access_paths, is_current_level_meta_access_path);
2292
22
    sub_predicate_access_paths.erase(removed.begin(), removed.end());
2293
2294
22
    if (sub_predicate_access_paths.empty()) {
2295
        // Check for meta-only modes (OFFSET_ONLY or NULL_MAP_ONLY). Only skip the item
2296
        // iterator when no predicate sub-path needs it in the predicate phase.
2297
10
        _check_and_set_meta_read_mode(requirement_before_access_path, sub_all_access_paths);
2298
10
        if (read_offset_only()) {
2299
0
            _item_iterator->set_read_requirement(ReadRequirement::SKIP);
2300
0
            DLOG(INFO) << "Array column iterator set column " << _column_name
2301
0
                       << " to OFFSET_ONLY meta read mode, item column set to SKIP";
2302
0
            return Status::OK();
2303
0
        }
2304
10
        if (read_null_map_only()) {
2305
2
            _item_iterator->set_read_requirement(ReadRequirement::SKIP);
2306
2
            DLOG(INFO) << "Array column iterator set column " << _column_name
2307
2
                       << " to NULL_MAP_ONLY meta read mode, item column set to SKIP";
2308
2
            return Status::OK();
2309
2
        }
2310
10
    }
2311
    // OFFSET/NULL at the current array level is consumed by this iterator. After deciding that
2312
    // the array is not in a meta-only mode, do not forward those paths to the item iterator.
2313
20
    remove_current_level_meta_access_paths(sub_all_access_paths);
2314
2315
20
    const auto no_sub_column_to_skip = sub_all_access_paths.empty();
2316
20
    const auto no_predicate_sub_column = sub_predicate_access_paths.empty();
2317
2318
20
    if (!no_sub_column_to_skip) {
2319
16
        for (auto& path : sub_all_access_paths) {
2320
16
            if (path.data_access_path.path[0] == ACCESS_ALL) {
2321
15
                path.data_access_path.path[0] = _item_iterator->column_name();
2322
15
            }
2323
16
        }
2324
16
    }
2325
2326
20
    if (no_predicate_sub_column) {
2327
        // Current-level predicate meta paths (OFFSET/NULL) are consumed by the array itself and
2328
        // removed before forwarding paths to the item iterator. If they are the only predicate
2329
        // paths, the item iterator may still be needed later for lazy materialization, but it must
2330
        // not be promoted to PREDICATE. Only propagate the predicate requirement when the
2331
        // parent predicate really applies to the item/whole value instead of array metadata only.
2332
8
        if (_read_requirement == ReadRequirement::PREDICATE &&
2333
8
            !has_current_level_predicate_meta_path) {
2334
2
            _item_iterator->set_read_requirement(ReadRequirement::PREDICATE);
2335
2
        }
2336
12
    } else {
2337
12
        for (auto& path : sub_predicate_access_paths) {
2338
12
            if (path.data_access_path.path[0] == ACCESS_ALL) {
2339
12
                path.data_access_path.path[0] = _item_iterator->column_name();
2340
12
            }
2341
12
        }
2342
12
    }
2343
2344
20
    if (!no_sub_column_to_skip || !no_predicate_sub_column) {
2345
18
        RETURN_IF_ERROR(
2346
18
                _item_iterator->set_access_paths(sub_all_access_paths, sub_predicate_access_paths));
2347
        // Predicate-only item paths stay PREDICATE because this update runs after
2348
        // child set_access_paths() and read requirements are monotonic. Non-predicate item paths are
2349
        // marked as lazy materialization targets.
2350
17
        _item_iterator->set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
2351
17
    }
2352
19
    return Status::OK();
2353
20
}
2354
2355
////////////////////////////////////////////////////////////////////////////////
2356
// StringFileColumnIterator implementation
2357
////////////////////////////////////////////////////////////////////////////////
2358
2359
StringFileColumnIterator::StringFileColumnIterator(std::shared_ptr<ColumnReader> reader)
2360
2.92k
        : FileColumnIterator(std::move(reader)) {}
2361
2362
2.90k
Status StringFileColumnIterator::init(const ColumnIteratorOptions& opts) {
2363
2.90k
    if (read_offset_only()) {
2364
        // Propagate only_read_offsets to the FileColumnIterator's options
2365
0
        auto modified_opts = opts;
2366
0
        modified_opts.only_read_offsets = true;
2367
0
        return FileColumnIterator::init(modified_opts);
2368
0
    }
2369
2.90k
    return FileColumnIterator::init(opts);
2370
2.90k
}
2371
2372
Status StringFileColumnIterator::set_access_paths(
2373
        const TColumnAccessPaths& all_access_paths,
2374
10
        const TColumnAccessPaths& predicate_access_paths) {
2375
10
    if (all_access_paths.empty() && predicate_access_paths.empty()) {
2376
0
        return Status::OK();
2377
0
    }
2378
2379
10
    const auto requirement_before_access_path = _read_requirement;
2380
10
    if (!predicate_access_paths.empty()) {
2381
8
        set_read_requirement(ReadRequirement::PREDICATE);
2382
8
    }
2383
2384
10
    const bool has_current_level_data_path =
2385
10
            std::ranges::any_of(all_access_paths, [this](const TColumnAccessPath& path) {
2386
10
                return is_current_level_data_access_path(path, _column_name);
2387
10
            });
2388
    // Strip the column name from path[0] before checking for meta-only modes.
2389
    // Raw paths look like ["col_name", "OFFSET"] or ["col_name", "NULL"].
2390
10
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
2391
10
    if (has_current_level_data_path) {
2392
2
        remove_current_level_meta_access_paths(sub_all_access_paths);
2393
2
    }
2394
10
    _check_and_set_meta_read_mode(requirement_before_access_path, sub_all_access_paths);
2395
    // OFFSET_ONLY mode is fundamentally incompatible with CHAR columns:
2396
    // CHAR is stored padded to its declared length (see
2397
    // OlapColumnDataConvertorChar::clone_and_padding), so the per-row length
2398
    // recorded in dict word info / page headers is always the padded length
2399
    // (e.g. 25 for CHAR(25)) — never the logical length expected by length().
2400
    // Recovering the logical length requires scanning the chars buffer with
2401
    // strnlen() (shrink_padding_chars), which OFFSET_ONLY by definition skips.
2402
    // There is no partial-benefit path: any optimization that still produces
2403
    // the correct length() result must read the chars buffer in full.
2404
    //
2405
    // FE (NestedColumnPruning) already filters CHAR slots out of the
2406
    // OFFSET-only access plan, so reaching this branch means an FE/BE
2407
    // contract violation. Fail loudly instead of silently falling back.
2408
10
    if (read_offset_only() && get_reader() != nullptr &&
2409
10
        get_reader()->get_meta_type() == FieldType::OLAP_FIELD_TYPE_CHAR) {
2410
0
        return Status::InternalError(
2411
0
                "OFFSET_ONLY access path is not supported on CHAR column '{}': CHAR is stored "
2412
0
                "padded so the per-row length information available without reading the chars "
2413
0
                "buffer is always the padded length, not the logical length. The FE planner "
2414
0
                "must not emit an OFFSET access path for CHAR columns.",
2415
0
                _column_name);
2416
0
    }
2417
10
    if (read_offset_only()) {
2418
2
        DLOG(INFO) << "String column iterator set column " << _column_name
2419
2
                   << " to OFFSET_ONLY meta read mode";
2420
8
    } else if (read_null_map_only()) {
2421
3
        DLOG(INFO) << "String column iterator set column " << _column_name
2422
3
                   << " to NULL_MAP_ONLY meta read mode";
2423
3
    }
2424
2425
10
    return Status::OK();
2426
10
}
2427
2428
////////////////////////////////////////////////////////////////////////////////
2429
2430
8.91k
FileColumnIterator::FileColumnIterator(std::shared_ptr<ColumnReader> reader) : _reader(reader) {}
2431
2432
void ColumnIterator::_check_and_set_meta_read_mode(ReadRequirement requirement_before_access_path,
2433
51
                                                   const TColumnAccessPaths& sub_all_access_paths) {
2434
51
    _meta_read_mode = MetaReadMode::DEFAULT;
2435
51
    if (requirement_before_access_path != ReadRequirement::NORMAL &&
2436
51
        requirement_before_access_path != ReadRequirement::SKIP) {
2437
        // A stronger requirement means a parent/full-data path already required this iterator
2438
        // to materialize data. In that case a later predicate NULL/OFFSET path is only
2439
        // an additional predicate requirement and must not downgrade the read to
2440
        // meta-only.
2441
6
        return;
2442
6
    }
2443
2444
45
    bool has_offset_path = false;
2445
45
    bool has_null_path = false;
2446
45
    for (const auto& path : sub_all_access_paths) {
2447
36
        if (!is_current_level_meta_access_path(path)) {
2448
20
            _meta_read_mode = MetaReadMode::DEFAULT;
2449
20
            return;
2450
20
        }
2451
16
        const auto& component = path.data_access_path.path[0];
2452
16
        if (StringCaseEqual()(component, ACCESS_OFFSET)) {
2453
5
            has_offset_path = true;
2454
11
        } else {
2455
11
            has_null_path = true;
2456
11
        }
2457
16
    }
2458
25
    if (has_offset_path) {
2459
        // OFFSET_ONLY skips actual child/string data, but nullable complex iterators still
2460
        // materialize the current-level null map. So OFFSET covers OFFSET+NULL metadata.
2461
4
        _meta_read_mode = MetaReadMode::OFFSET_ONLY;
2462
21
    } else if (has_null_path) {
2463
10
        _meta_read_mode = MetaReadMode::NULL_MAP_ONLY;
2464
11
    } else {
2465
11
        _meta_read_mode = MetaReadMode::DEFAULT;
2466
11
    }
2467
25
}
2468
2469
8.57k
Status FileColumnIterator::init(const ColumnIteratorOptions& opts) {
2470
8.57k
    if (_read_requirement == ReadRequirement::SKIP) {
2471
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2472
0
        return Status::OK();
2473
0
    }
2474
2475
8.57k
    _opts = opts;
2476
8.57k
    if (!_opts.use_page_cache) {
2477
8.57k
        _reader->disable_index_meta_cache();
2478
8.57k
    }
2479
8.57k
    RETURN_IF_ERROR(get_block_compression_codec(_reader->get_compression(), &_compress_codec));
2480
8.57k
    if (config::enable_low_cardinality_optimize &&
2481
8.57k
        opts.io_ctx.reader_type == ReaderType::READER_QUERY &&
2482
8.57k
        _reader->encoding_info()->encoding() == DICT_ENCODING) {
2483
139
        auto dict_encoding_type = _reader->get_dict_encoding_type();
2484
        // Only if the column is a predicate column, then we need check the all dict encoding flag
2485
        // because we could rewrite the predciate to accelarate query speed. But if it is not a
2486
        // predicate column, then it is useless. And it has a bad impact on cold read(first time read)
2487
        // because it will load the column's ordinal index and zonemap index and maybe other indices.
2488
        // it has bad impact on primary key query. For example, select * from table where pk = 1, and
2489
        // the table has 2000 columns.
2490
139
        if (dict_encoding_type == ColumnReader::UNKNOWN_DICT_ENCODING && opts.is_predicate_column) {
2491
33
            RETURN_IF_ERROR(seek_to_ordinal(_reader->num_rows() - 1));
2492
33
            _is_all_dict_encoding = _page.is_dict_encoding;
2493
33
            _reader->set_dict_encoding_type(_is_all_dict_encoding
2494
33
                                                    ? ColumnReader::ALL_DICT_ENCODING
2495
33
                                                    : ColumnReader::PARTIAL_DICT_ENCODING);
2496
106
        } else {
2497
106
            _is_all_dict_encoding = dict_encoding_type == ColumnReader::ALL_DICT_ENCODING;
2498
106
        }
2499
139
    }
2500
8.57k
    return Status::OK();
2501
8.57k
}
2502
2503
8.91k
FileColumnIterator::~FileColumnIterator() = default;
2504
2505
0
void FileColumnIterator::_trigger_prefetch_if_eligible(ordinal_t ord) {
2506
0
    std::vector<BlockRange> ranges;
2507
0
    if (_prefetcher->need_prefetch(cast_set<uint32_t>(ord), &ranges)) {
2508
0
        for (const auto& range : ranges) {
2509
0
            _cached_remote_file_reader->prefetch_range(range.offset, range.size, &_opts.io_ctx);
2510
0
        }
2511
0
    }
2512
0
}
2513
2514
24.4k
Status FileColumnIterator::seek_to_ordinal(ordinal_t ord) {
2515
24.4k
    if (!need_to_read()) {
2516
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2517
0
        return Status::OK();
2518
0
    }
2519
2520
24.4k
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
2521
0
            "[verbose] FileColumnIterator::seek_to_ordinal seek to ordinal {}, enable_prefetch={}",
2522
0
            ord, _enable_prefetch);
2523
24.4k
    if (_enable_prefetch) {
2524
0
        _trigger_prefetch_if_eligible(ord);
2525
0
    }
2526
2527
    // if current page contains this row, we don't need to seek
2528
24.4k
    if (!_page || !_page.contains(ord) || !_page_iter.valid()) {
2529
9.04k
        RETURN_IF_ERROR(_reader->seek_at_or_before(ord, &_page_iter, _opts));
2530
9.04k
        RETURN_IF_ERROR(_read_data_page(_page_iter));
2531
9.04k
    }
2532
24.4k
    RETURN_IF_ERROR(_seek_to_pos_in_page(&_page, ord - _page.first_ordinal));
2533
24.4k
    _current_ordinal = ord;
2534
24.4k
    return Status::OK();
2535
24.4k
}
2536
2537
0
Status FileColumnIterator::seek_to_page_start() {
2538
0
    return seek_to_ordinal(_page.first_ordinal);
2539
0
}
2540
2541
26.2k
Status FileColumnIterator::_seek_to_pos_in_page(ParsedPage* page, ordinal_t offset_in_page) const {
2542
26.2k
    if (page->offset_in_page == offset_in_page) {
2543
        // fast path, do nothing
2544
22.9k
        return Status::OK();
2545
22.9k
    }
2546
2547
3.25k
    ordinal_t pos_in_data = offset_in_page;
2548
3.25k
    if (_page.has_null) {
2549
6
        ordinal_t offset_in_data = 0;
2550
6
        ordinal_t skips = offset_in_page;
2551
2552
6
        if (offset_in_page > page->offset_in_page) {
2553
            // forward, reuse null bitmap
2554
3
            skips = offset_in_page - page->offset_in_page;
2555
3
            offset_in_data = page->data_decoder->current_index();
2556
3
        } else {
2557
            // rewind null bitmap, and
2558
3
            page->null_decoder = RleDecoder<bool>((const uint8_t*)page->null_bitmap.data,
2559
3
                                                  cast_set<int>(page->null_bitmap.size), 1);
2560
3
        }
2561
2562
6
        auto skip_nulls = page->null_decoder.Skip(skips);
2563
6
        pos_in_data = offset_in_data + skips - skip_nulls;
2564
6
    }
2565
2566
3.25k
    RETURN_IF_ERROR(page->data_decoder->seek_to_position_in_page(pos_in_data));
2567
3.25k
    page->offset_in_page = offset_in_page;
2568
3.25k
    return Status::OK();
2569
3.25k
}
2570
2571
0
Status FileColumnIterator::next_batch_of_zone_map(size_t* n, MutableColumnPtr& dst) {
2572
0
    return _reader->next_batch_of_zone_map(n, dst);
2573
0
}
2574
2575
20.4k
Status FileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
2576
20.4k
    if (!need_to_read()) {
2577
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2578
0
        _convert_to_place_holder_column(dst, *n);
2579
0
        return Status::OK();
2580
0
    }
2581
2582
20.4k
    _recovery_from_place_holder_column(dst);
2583
2584
20.4k
    if (read_null_map_only()) {
2585
0
        DLOG(INFO) << "File column iterator column " << _column_name
2586
0
                   << " in NULL_MAP_ONLY mode, reading only null map.";
2587
0
        DORIS_CHECK(is_column_nullable(*dst));
2588
0
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
2589
0
        auto& null_map_data = nullable_col.get_null_map_data();
2590
2591
0
        size_t remaining = *n;
2592
0
        *has_null = false;
2593
0
        while (remaining > 0) {
2594
0
            if (!_page.has_remaining()) {
2595
0
                bool eos = false;
2596
0
                RETURN_IF_ERROR(_load_next_page(&eos));
2597
0
                if (eos) {
2598
0
                    break;
2599
0
                }
2600
0
            }
2601
2602
0
            size_t nrows_in_page = std::min(remaining, _page.remaining());
2603
0
            size_t nrows_to_read = nrows_in_page;
2604
0
            if (_page.has_null) {
2605
0
                while (nrows_to_read > 0) {
2606
0
                    bool is_null = false;
2607
0
                    size_t this_run = _page.null_decoder.GetNextRun(&is_null, nrows_to_read);
2608
0
                    const size_t cur_size = null_map_data.size();
2609
0
                    null_map_data.resize(cur_size + this_run);
2610
0
                    memset(null_map_data.data() + cur_size, is_null ? 1 : 0, this_run);
2611
0
                    if (is_null) {
2612
0
                        *has_null = true;
2613
0
                    }
2614
0
                    nrows_to_read -= this_run;
2615
0
                    _page.offset_in_page += this_run;
2616
0
                    _current_ordinal += this_run;
2617
0
                }
2618
0
            } else {
2619
0
                const size_t cur_size = null_map_data.size();
2620
0
                null_map_data.resize(cur_size + nrows_to_read);
2621
0
                memset(null_map_data.data() + cur_size, 0, nrows_to_read);
2622
0
                _page.offset_in_page += nrows_to_read;
2623
0
                _current_ordinal += nrows_to_read;
2624
0
            }
2625
0
            remaining -= nrows_in_page;
2626
0
        }
2627
0
        *n -= remaining;
2628
0
        nullable_col.get_nested_column().insert_many_defaults(*n);
2629
0
        return Status::OK();
2630
0
    }
2631
2632
20.4k
    size_t curr_size = dst->byte_size();
2633
20.4k
    dst->reserve(*n);
2634
20.4k
    size_t remaining = *n;
2635
20.4k
    *has_null = false;
2636
42.6k
    while (remaining > 0) {
2637
22.2k
        if (!_page.has_remaining()) {
2638
1.76k
            bool eos = false;
2639
1.76k
            RETURN_IF_ERROR(_load_next_page(&eos));
2640
1.76k
            if (eos) {
2641
0
                break;
2642
0
            }
2643
1.76k
        }
2644
2645
        // number of rows to be read from this page
2646
22.2k
        size_t nrows_in_page = std::min(remaining, _page.remaining());
2647
22.2k
        size_t nrows_to_read = nrows_in_page;
2648
22.2k
        if (_page.has_null) {
2649
20.7k
            while (nrows_to_read > 0) {
2650
20.4k
                bool is_null = false;
2651
20.4k
                size_t this_run = _page.null_decoder.GetNextRun(&is_null, nrows_to_read);
2652
                // we use num_rows only for CHECK
2653
20.4k
                size_t num_rows = this_run;
2654
20.4k
                if (!is_null) {
2655
10.3k
                    RETURN_IF_ERROR(_page.data_decoder->next_batch(&num_rows, dst));
2656
10.3k
                    DCHECK_EQ(this_run, num_rows);
2657
10.3k
                } else {
2658
10.1k
                    *has_null = true;
2659
10.1k
                    auto* null_col = check_and_get_column<ColumnNullable>(dst.get());
2660
10.1k
                    if (null_col != nullptr) {
2661
10.1k
                        null_col->insert_many_defaults(this_run);
2662
10.1k
                    } else {
2663
0
                        return Status::InternalError("unexpected column type in column reader");
2664
0
                    }
2665
10.1k
                }
2666
2667
20.4k
                nrows_to_read -= this_run;
2668
20.4k
                _page.offset_in_page += this_run;
2669
20.4k
                _current_ordinal += this_run;
2670
20.4k
            }
2671
21.9k
        } else {
2672
21.9k
            RETURN_IF_ERROR(_page.data_decoder->next_batch(&nrows_to_read, dst));
2673
21.9k
            DCHECK_EQ(nrows_to_read, nrows_in_page);
2674
2675
21.9k
            _page.offset_in_page += nrows_to_read;
2676
21.9k
            _current_ordinal += nrows_to_read;
2677
21.9k
        }
2678
22.2k
        remaining -= nrows_in_page;
2679
22.2k
    }
2680
20.4k
    *n -= remaining;
2681
20.4k
    _opts.stats->bytes_read += (dst->byte_size() - curr_size) + BitmapSize(*n);
2682
2683
20.4k
#ifdef BE_TEST
2684
20.4k
    _reader->check_data_by_zone_map_for_test(dst);
2685
20.4k
#endif
2686
20.4k
    return Status::OK();
2687
20.4k
}
2688
2689
Status FileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
2690
3.47k
                                          MutableColumnPtr& dst) {
2691
3.47k
    if (!need_to_read()) {
2692
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2693
0
        _convert_to_place_holder_column(dst, count);
2694
0
        return Status::OK();
2695
0
    }
2696
2697
3.47k
    _recovery_from_place_holder_column(dst);
2698
2699
3.47k
    if (read_null_map_only()) {
2700
1
        DLOG(INFO) << "File column iterator column " << _column_name
2701
1
                   << " in NULL_MAP_ONLY mode, reading only null map by rowids.";
2702
2703
1
        DORIS_CHECK(is_column_nullable(*dst));
2704
1
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
2705
1
        auto& null_map_data = nullable_col.get_null_map_data();
2706
1
        const size_t base_size = null_map_data.size();
2707
1
        null_map_data.resize(base_size + count);
2708
2709
1
        size_t remaining = count;
2710
1
        size_t total_read_count = 0;
2711
1
        size_t nrows_to_read = 0;
2712
3
        while (remaining > 0) {
2713
2
            RETURN_IF_ERROR(seek_to_ordinal(rowids[total_read_count]));
2714
2715
2
            nrows_to_read = std::min(remaining, _page.remaining());
2716
2717
2
            if (_page.has_null) {
2718
1
                size_t already_read = 0;
2719
2
                while ((nrows_to_read - already_read) > 0) {
2720
1
                    bool is_null = false;
2721
1
                    size_t this_run = std::min(nrows_to_read - already_read, _page.remaining());
2722
1
                    if (UNLIKELY(this_run == 0)) {
2723
0
                        break;
2724
0
                    }
2725
1
                    this_run = _page.null_decoder.GetNextRun(&is_null, this_run);
2726
2727
1
                    size_t offset = total_read_count + already_read;
2728
1
                    size_t this_read_count = 0;
2729
1
                    rowid_t current_ordinal_in_page =
2730
1
                            cast_set<uint32_t>(_page.offset_in_page + _page.first_ordinal);
2731
2
                    for (size_t i = 0; i < this_run; ++i) {
2732
1
                        if (rowids[offset + i] - current_ordinal_in_page >= this_run) {
2733
0
                            break;
2734
0
                        }
2735
1
                        this_read_count++;
2736
1
                    }
2737
2738
1
                    if (this_read_count > 0) {
2739
1
                        memset(null_map_data.data() + base_size + offset, is_null ? 1 : 0,
2740
1
                               this_read_count);
2741
1
                    }
2742
2743
1
                    already_read += this_read_count;
2744
1
                    _page.offset_in_page += this_run;
2745
1
                }
2746
2747
1
                nrows_to_read = already_read;
2748
1
                total_read_count += nrows_to_read;
2749
1
                remaining -= nrows_to_read;
2750
1
            } else {
2751
1
                rowid_t current_ordinal_in_page =
2752
1
                        cast_set<uint32_t>(_page.offset_in_page + _page.first_ordinal);
2753
1
                size_t rows_in_current_page = 0;
2754
2
                for (size_t i = 0; i < nrows_to_read; ++i) {
2755
2
                    if (rowids[total_read_count + i] - current_ordinal_in_page >= nrows_to_read) {
2756
1
                        break;
2757
1
                    }
2758
1
                    ++rows_in_current_page;
2759
1
                }
2760
1
                DCHECK_GT(rows_in_current_page, 0);
2761
1
                memset(null_map_data.data() + base_size + total_read_count, 0,
2762
1
                       rows_in_current_page);
2763
1
                _page.offset_in_page += rows_in_current_page;
2764
1
                total_read_count += rows_in_current_page;
2765
1
                remaining -= rows_in_current_page;
2766
1
            }
2767
2
        }
2768
2769
1
        null_map_data.resize(base_size + total_read_count);
2770
1
        nullable_col.get_nested_column().insert_many_defaults(total_read_count);
2771
1
        return Status::OK();
2772
1
    }
2773
2774
3.47k
    size_t remaining = count;
2775
3.47k
    size_t total_read_count = 0;
2776
3.47k
    size_t nrows_to_read = 0;
2777
7.46k
    while (remaining > 0) {
2778
3.98k
        RETURN_IF_ERROR(seek_to_ordinal(rowids[total_read_count]));
2779
2780
        // number of rows to be read from this page
2781
3.98k
        nrows_to_read = std::min(remaining, _page.remaining());
2782
2783
3.98k
        if (_page.has_null) {
2784
10
            size_t already_read = 0;
2785
754
            while ((nrows_to_read - already_read) > 0) {
2786
744
                bool is_null = false;
2787
744
                size_t this_run = std::min(nrows_to_read - already_read, _page.remaining());
2788
744
                if (UNLIKELY(this_run == 0)) {
2789
0
                    break;
2790
0
                }
2791
744
                this_run = _page.null_decoder.GetNextRun(&is_null, this_run);
2792
744
                size_t offset = total_read_count + already_read;
2793
744
                size_t this_read_count = 0;
2794
744
                rowid_t current_ordinal_in_page =
2795
744
                        cast_set<uint32_t>(_page.offset_in_page + _page.first_ordinal);
2796
2.03k
                for (size_t i = 0; i < this_run; ++i) {
2797
1.80k
                    if (rowids[offset + i] - current_ordinal_in_page >= this_run) {
2798
510
                        break;
2799
510
                    }
2800
1.29k
                    this_read_count++;
2801
1.29k
                }
2802
2803
744
                auto origin_index = _page.data_decoder->current_index();
2804
744
                if (this_read_count > 0) {
2805
405
                    if (is_null) {
2806
141
                        auto* null_col = check_and_get_column<ColumnNullable>(dst.get());
2807
141
                        if (UNLIKELY(null_col == nullptr)) {
2808
0
                            return Status::InternalError("unexpected column type in column reader");
2809
0
                        }
2810
2811
141
                        null_col->insert_many_defaults(this_read_count);
2812
264
                    } else {
2813
264
                        size_t read_count = this_read_count;
2814
2815
                        // ordinal in nullable columns' data buffer maybe be not continuously(the data doesn't contain null value),
2816
                        // so we need use `page_start_off_in_decoder` to calculate the actual offset in `data_decoder`
2817
264
                        size_t page_start_off_in_decoder =
2818
264
                                _page.first_ordinal + _page.offset_in_page - origin_index;
2819
264
                        RETURN_IF_ERROR(_page.data_decoder->read_by_rowids(
2820
264
                                &rowids[offset], page_start_off_in_decoder, &read_count, dst));
2821
264
                        DCHECK_EQ(read_count, this_read_count);
2822
264
                    }
2823
405
                }
2824
2825
744
                if (!is_null) {
2826
383
                    RETURN_IF_ERROR(
2827
383
                            _page.data_decoder->seek_to_position_in_page(origin_index + this_run));
2828
383
                }
2829
2830
744
                already_read += this_read_count;
2831
744
                _page.offset_in_page += this_run;
2832
744
                DCHECK(_page.offset_in_page <= _page.num_rows);
2833
744
            }
2834
2835
10
            nrows_to_read = already_read;
2836
10
            total_read_count += nrows_to_read;
2837
10
            remaining -= nrows_to_read;
2838
3.97k
        } else {
2839
3.97k
            RETURN_IF_ERROR(_page.data_decoder->read_by_rowids(
2840
3.97k
                    &rowids[total_read_count], _page.first_ordinal, &nrows_to_read, dst));
2841
3.97k
            total_read_count += nrows_to_read;
2842
3.97k
            remaining -= nrows_to_read;
2843
3.97k
        }
2844
3.98k
    }
2845
3.47k
    return Status::OK();
2846
3.47k
}
2847
2848
1.76k
Status FileColumnIterator::_load_next_page(bool* eos) {
2849
1.76k
    _page_iter.next();
2850
1.76k
    if (!_page_iter.valid()) {
2851
0
        *eos = true;
2852
0
        return Status::OK();
2853
0
    }
2854
2855
1.76k
    RETURN_IF_ERROR(_read_data_page(_page_iter));
2856
1.76k
    RETURN_IF_ERROR(_seek_to_pos_in_page(&_page, 0));
2857
1.76k
    *eos = false;
2858
1.76k
    return Status::OK();
2859
1.76k
}
2860
2861
10.8k
Status FileColumnIterator::_read_data_page(const OrdinalPageIndexIterator& iter) {
2862
10.8k
    PageHandle handle;
2863
10.8k
    Slice page_body;
2864
10.8k
    PageFooterPB footer;
2865
10.8k
    _opts.type = DATA_PAGE;
2866
10.8k
    PageDecoderOptions decoder_opts;
2867
10.8k
    decoder_opts.only_read_offsets = _opts.only_read_offsets;
2868
10.8k
    RETURN_IF_ERROR(
2869
10.8k
            _reader->read_page(_opts, iter.page(), &handle, &page_body, &footer, _compress_codec));
2870
    // parse data page
2871
10.8k
    auto st = ParsedPage::create(std::move(handle), page_body, footer.data_page_footer(),
2872
10.8k
                                 _reader->encoding_info(), iter.page(), iter.page_index(), &_page,
2873
10.8k
                                 decoder_opts);
2874
10.8k
    if (!st.ok()) {
2875
0
        LOG(WARNING) << "failed to create ParsedPage, file=" << _opts.file_reader->path().native()
2876
0
                     << ", page_offset=" << iter.page().offset << ", page_size=" << iter.page().size
2877
0
                     << ", page_index=" << iter.page_index() << ", error=" << st;
2878
0
        return st;
2879
0
    }
2880
2881
    // dictionary page is read when the first data page that uses it is read,
2882
    // this is to optimize the memory usage: when there is no query on one column, we could
2883
    // release the memory of dictionary page.
2884
    // note that concurrent iterators for the same column won't repeatedly read dictionary page
2885
    // because of page cache.
2886
10.8k
    if (_reader->encoding_info()->encoding() == DICT_ENCODING) {
2887
4.71k
        auto dict_page_decoder = reinterpret_cast<BinaryDictPageDecoder*>(_page.data_decoder.get());
2888
4.71k
        if (dict_page_decoder->is_dict_encoding()) {
2889
3.08k
            if (_dict_decoder == nullptr) {
2890
3.08k
                RETURN_IF_ERROR(_read_dict_data());
2891
3.08k
                CHECK_NOTNULL(_dict_decoder);
2892
3.08k
            }
2893
2894
3.08k
            dict_page_decoder->set_dict_decoder(cast_set<uint32_t>(_dict_decoder->count()),
2895
3.08k
                                                _dict_word_info.get());
2896
3.08k
        }
2897
4.71k
    }
2898
10.8k
    return Status::OK();
2899
10.8k
}
2900
2901
3.08k
Status FileColumnIterator::_read_dict_data() {
2902
3.08k
    CHECK_EQ(_reader->encoding_info()->encoding(), DICT_ENCODING);
2903
    // read dictionary page
2904
3.08k
    Slice dict_data;
2905
3.08k
    PageFooterPB dict_footer;
2906
3.08k
    _opts.type = INDEX_PAGE;
2907
2908
3.08k
    RETURN_IF_ERROR(_reader->read_page(_opts, _reader->get_dict_page_pointer(), &_dict_page_handle,
2909
3.08k
                                       &dict_data, &dict_footer, _compress_codec));
2910
3.08k
    const EncodingInfo* encoding_info;
2911
    // The dict pool stores strings of the outer column's type. Using the
2912
    // outer type (CHAR vs VARCHAR/STRING) lets the EncodingInfo pick a
2913
    // CHAR-strip pre-decoder so the cached dict page is already unpadded.
2914
3.08k
    RETURN_IF_ERROR(EncodingInfo::get(_reader->get_meta_type(),
2915
3.08k
                                      dict_footer.dict_page_footer().encoding(), &encoding_info));
2916
3.08k
    RETURN_IF_ERROR(encoding_info->create_page_decoder(dict_data, {}, _dict_decoder));
2917
3.08k
    RETURN_IF_ERROR(_dict_decoder->init());
2918
2919
3.08k
    _dict_word_info.reset(new StringRef[_dict_decoder->count()]);
2920
3.08k
    RETURN_IF_ERROR(_dict_decoder->get_dict_word_info(_dict_word_info.get()));
2921
3.08k
    return Status::OK();
2922
3.08k
}
2923
2924
Status FileColumnIterator::get_row_ranges_by_zone_map(
2925
        const AndBlockColumnPredicate* col_predicates,
2926
        const std::vector<std::shared_ptr<const ColumnPredicate>>* delete_predicates,
2927
64
        RowRanges* row_ranges) {
2928
64
    if (_reader->has_zone_map()) {
2929
64
        RETURN_IF_ERROR(_reader->get_row_ranges_by_zone_map(col_predicates, delete_predicates,
2930
64
                                                            row_ranges, _opts));
2931
64
    }
2932
64
    return Status::OK();
2933
64
}
2934
2935
Status FileColumnIterator::get_row_ranges_by_bloom_filter(
2936
64
        const AndBlockColumnPredicate* col_predicates, RowRanges* row_ranges) {
2937
64
    if ((col_predicates->can_do_bloom_filter(false) && _reader->has_bloom_filter_index(false)) ||
2938
64
        (col_predicates->can_do_bloom_filter(true) && _reader->has_bloom_filter_index(true))) {
2939
3
        RETURN_IF_ERROR(_reader->get_row_ranges_by_bloom_filter(col_predicates, row_ranges, _opts));
2940
3
    }
2941
64
    return Status::OK();
2942
64
}
2943
2944
Status FileColumnIterator::get_row_ranges_by_dict(const AndBlockColumnPredicate* col_predicates,
2945
64
                                                  RowRanges* row_ranges) {
2946
64
    if (!_is_all_dict_encoding) {
2947
31
        return Status::OK();
2948
31
    }
2949
2950
33
    if (!_dict_decoder) {
2951
0
        RETURN_IF_ERROR(_read_dict_data());
2952
0
        CHECK_NOTNULL(_dict_decoder);
2953
0
    }
2954
2955
33
    if (!col_predicates->evaluate_and(_dict_word_info.get(), _dict_decoder->count())) {
2956
0
        row_ranges->clear();
2957
0
    }
2958
33
    return Status::OK();
2959
33
}
2960
2961
0
Status FileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
2962
0
    if (_cached_remote_file_reader =
2963
0
                std::dynamic_pointer_cast<io::CachedRemoteFileReader>(_reader->_file_reader);
2964
0
        !_cached_remote_file_reader) {
2965
0
        return Status::OK();
2966
0
    }
2967
0
    _enable_prefetch = true;
2968
0
    _prefetcher = std::make_unique<SegmentPrefetcher>(params.config);
2969
0
    RETURN_IF_ERROR(_prefetcher->init(_reader, params.read_options));
2970
0
    return Status::OK();
2971
0
}
2972
2973
void FileColumnIterator::collect_prefetchers(
2974
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
2975
0
        PrefetcherInitMethod init_method) {
2976
0
    if (_prefetcher) {
2977
0
        prefetchers[init_method].emplace_back(_prefetcher.get());
2978
0
    }
2979
0
}
2980
2981
25
Status DefaultValueColumnIterator::init(const ColumnIteratorOptions& opts) {
2982
25
    _opts = opts;
2983
    // be consistent with segment v1
2984
    // if _has_default_value, we should create default column iterator for this column, and
2985
    // "NULL" is a special default value which means the default value is null.
2986
25
    if (_has_default_value) {
2987
1
        if (_default_value == "NULL") {
2988
1
            _default_value_field = Field::create_field<TYPE_NULL>(Null {});
2989
1
        } else {
2990
0
            if (_type == FieldType::OLAP_FIELD_TYPE_ARRAY) {
2991
0
                if (_default_value != "[]") {
2992
0
                    return Status::NotSupported("Array default {} is unsupported", _default_value);
2993
0
                } else {
2994
0
                    _default_value_field = Field::create_field<TYPE_ARRAY>(Array {});
2995
0
                    return Status::OK();
2996
0
                }
2997
0
            } else if (_type == FieldType::OLAP_FIELD_TYPE_STRUCT) {
2998
0
                return Status::NotSupported("STRUCT default type is unsupported");
2999
0
            } else if (_type == FieldType::OLAP_FIELD_TYPE_MAP) {
3000
0
                return Status::NotSupported("MAP default type is unsupported");
3001
0
            }
3002
0
            const auto t = _type;
3003
0
            const auto serde = DataTypeFactory::instance()
3004
0
                                       .create_data_type(t, _precision, _scale, _len)
3005
0
                                       ->get_serde();
3006
0
            RETURN_IF_ERROR(serde->from_fe_string(_default_value, _default_value_field));
3007
0
        }
3008
24
    } else if (_is_nullable) {
3009
24
        _default_value_field = Field::create_field<TYPE_NULL>(Null {});
3010
24
    } else {
3011
0
        return Status::InternalError(
3012
0
                "invalid default value column for no default value and not nullable");
3013
0
    }
3014
25
    return Status::OK();
3015
25
}
3016
3017
8
Status DefaultValueColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
3018
8
    *has_null = _default_value_field.is_null();
3019
8
    _insert_many_default(dst, *n);
3020
8
    return Status::OK();
3021
8
}
3022
3023
Status DefaultValueColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
3024
3
                                                  MutableColumnPtr& dst) {
3025
3
    _insert_many_default(dst, count);
3026
3
    return Status::OK();
3027
3
}
3028
3029
11
void DefaultValueColumnIterator::_insert_many_default(MutableColumnPtr& dst, size_t n) {
3030
11
    if (_default_value_field.is_null()) {
3031
11
        dst->insert_many_defaults(n);
3032
11
    } else {
3033
0
        dst = dst->convert_to_predicate_column_if_dictionary();
3034
0
        dst->insert_duplicate_fields(_default_value_field, n);
3035
0
    }
3036
11
}
3037
3038
0
Status RowIdColumnIteratorV2::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
3039
0
    auto* string_column = assert_cast<ColumnString*, TypeCheckOnRelease::DISABLE>(dst.get());
3040
3041
0
    for (uint32_t i = 0; i < *n; ++i) {
3042
0
        uint32_t row_id = _current_rowid + i;
3043
0
        GlobalRowLoacationV2 location(_version, _backend_id, _file_id, row_id);
3044
0
        string_column->insert_data(reinterpret_cast<const char*>(&location),
3045
0
                                   sizeof(GlobalRowLoacationV2));
3046
0
    }
3047
0
    _current_rowid += *n;
3048
0
    return Status::OK();
3049
0
}
3050
3051
Status RowIdColumnIteratorV2::read_by_rowids(const rowid_t* rowids, const size_t count,
3052
16
                                             MutableColumnPtr& dst) {
3053
16
    auto* string_column = assert_cast<ColumnString*>(dst.get());
3054
3055
41
    for (size_t i = 0; i < count; ++i) {
3056
25
        uint32_t row_id = rowids[i];
3057
25
        GlobalRowLoacationV2 location(_version, _backend_id, _file_id, row_id);
3058
25
        string_column->insert_data(reinterpret_cast<const char*>(&location),
3059
25
                                   sizeof(GlobalRowLoacationV2));
3060
25
    }
3061
16
    return Status::OK();
3062
16
}
3063
3064
} // namespace doris::segment_v2