Coverage Report

Created: 2026-07-15 13:51

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
175
bool is_current_level_meta_access_path(const TColumnAccessPath& path) {
94
175
    if (path.data_access_path.path.size() != 1) {
95
91
        return false;
96
91
    }
97
84
    const auto& component = path.data_access_path.path[0];
98
84
    return StringCaseEqual()(component, ColumnIterator::ACCESS_OFFSET) ||
99
84
           StringCaseEqual()(component, ColumnIterator::ACCESS_NULL);
100
175
}
101
102
bool is_current_level_data_access_path(const TColumnAccessPath& path,
103
94
                                       const std::string& column_name) {
104
94
    return path.data_access_path.path.size() == 1 &&
105
94
           StringCaseEqual()(path.data_access_path.path[0], column_name);
106
94
}
107
108
101
void remove_current_level_meta_access_paths(TColumnAccessPaths& paths) {
109
101
    auto removed = std::ranges::remove_if(paths, is_current_level_meta_access_path);
110
101
    paths.erase(removed.begin(), removed.end());
111
101
}
112
113
Status ColumnReader::create_array(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
114
                                  const io::FileReaderSPtr& file_reader,
115
37
                                  std::shared_ptr<ColumnReader>* reader) {
116
37
    DCHECK(meta.children_columns_size() == 2 || meta.children_columns_size() == 3);
117
118
37
    std::shared_ptr<ColumnReader> item_reader;
119
37
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(0),
120
37
                                         meta.children_columns(0).num_rows(), file_reader,
121
37
                                         &item_reader));
122
123
37
    std::shared_ptr<ColumnReader> offset_reader;
124
37
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(1),
125
37
                                         meta.children_columns(1).num_rows(), file_reader,
126
37
                                         &offset_reader));
127
128
37
    std::shared_ptr<ColumnReader> null_reader;
129
37
    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
37
    uint64_t array_num_rows = meta.children_columns(1).num_rows();
137
37
    std::shared_ptr<ColumnReader> array_reader(
138
37
            new ColumnReader(opts, meta, array_num_rows, file_reader));
139
    //  array reader do not need to init
140
37
    array_reader->_sub_readers.resize(meta.children_columns_size());
141
37
    array_reader->_sub_readers[0] = std::move(item_reader);
142
37
    array_reader->_sub_readers[1] = std::move(offset_reader);
143
37
    if (meta.is_nullable()) {
144
33
        array_reader->_sub_readers[2] = std::move(null_reader);
145
33
    }
146
37
    array_reader->_meta_type = FieldType::OLAP_FIELD_TYPE_ARRAY;
147
37
    *reader = std::move(array_reader);
148
37
    return Status::OK();
149
37
}
150
151
Status ColumnReader::create_map(const ColumnReaderOptions& opts, const ColumnMetaPB& meta,
152
                                const io::FileReaderSPtr& file_reader,
153
785
                                std::shared_ptr<ColumnReader>* reader) {
154
    // map reader now has 3 sub readers for key, value, offsets(scalar), null(scala)
155
785
    DCHECK(meta.children_columns_size() == 3 || meta.children_columns_size() == 4);
156
785
    std::shared_ptr<ColumnReader> key_reader;
157
785
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(0),
158
785
                                         meta.children_columns(0).num_rows(), file_reader,
159
785
                                         &key_reader));
160
785
    std::shared_ptr<ColumnReader> val_reader;
161
785
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(1),
162
785
                                         meta.children_columns(1).num_rows(), file_reader,
163
785
                                         &val_reader));
164
785
    std::shared_ptr<ColumnReader> offset_reader;
165
785
    RETURN_IF_ERROR(ColumnReader::create(opts, meta.children_columns(2),
166
785
                                         meta.children_columns(2).num_rows(), file_reader,
167
785
                                         &offset_reader));
168
785
    std::shared_ptr<ColumnReader> null_reader;
169
785
    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
785
    uint64_t map_num_rows = meta.children_columns(2).num_rows();
177
785
    std::shared_ptr<ColumnReader> map_reader(
178
785
            new ColumnReader(opts, meta, map_num_rows, file_reader));
179
785
    map_reader->_sub_readers.resize(meta.children_columns_size());
180
181
785
    map_reader->_sub_readers[0] = std::move(key_reader);
182
785
    map_reader->_sub_readers[1] = std::move(val_reader);
183
785
    map_reader->_sub_readers[2] = std::move(offset_reader);
184
785
    if (meta.is_nullable()) {
185
0
        map_reader->_sub_readers[3] = std::move(null_reader);
186
0
    }
187
785
    map_reader->_meta_type = FieldType::OLAP_FIELD_TYPE_MAP;
188
785
    *reader = std::move(map_reader);
189
785
    return Status::OK();
190
785
}
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.8k
                            std::shared_ptr<ColumnReader>* reader) {
259
11.8k
    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.8k
    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.55k
        auto type = (FieldType)meta.type();
271
1.55k
        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
37
        case FieldType::OLAP_FIELD_TYPE_ARRAY: {
279
37
            return create_array(opts, meta, file_reader, reader);
280
0
        }
281
785
        case FieldType::OLAP_FIELD_TYPE_MAP: {
282
785
            return create_map(opts, meta, file_reader, reader);
283
0
        }
284
733
        case FieldType::OLAP_FIELD_TYPE_VARIANT: {
285
            // Read variant only root data using a single ColumnReader
286
733
            std::shared_ptr<ColumnReader> reader_local(
287
733
                    new ColumnReader(opts, meta, num_rows, file_reader));
288
733
            RETURN_IF_ERROR(reader_local->init(&meta));
289
733
            *reader = std::move(reader_local);
290
733
            return Status::OK();
291
733
        }
292
0
        default:
293
0
            return Status::NotSupported("unsupported type for ColumnReader: {}",
294
0
                                        std::to_string(int(type)));
295
1.55k
        }
296
1.55k
    }
297
11.8k
}
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.8k
        : _use_index_page_cache(!config::disable_storage_page_cache),
304
11.8k
          _opts(opts),
305
11.8k
          _num_rows(num_rows),
306
11.8k
          _file_reader(std::move(file_reader)),
307
11.8k
          _dict_encoding_type(UNKNOWN_DICT_ENCODING) {
308
11.8k
    _meta_length = meta.length();
309
11.8k
    _meta_type = (FieldType)meta.type();
310
11.8k
    if (_meta_type == FieldType::OLAP_FIELD_TYPE_ARRAY) {
311
37
        _meta_children_column_type = (FieldType)meta.children_columns(0).type();
312
37
    }
313
11.8k
    _data_type = DataTypeFactory::instance().create_data_type(meta);
314
11.8k
    _meta_is_nullable = meta.is_nullable();
315
11.8k
    _meta_dict_page = meta.dict_page();
316
11.8k
    _meta_compression = meta.compression();
317
11.8k
}
318
319
13.0k
ColumnReader::~ColumnReader() = default;
320
321
11.2k
int64_t ColumnReader::get_metadata_size() const {
322
11.2k
    return sizeof(ColumnReader) + (_segment_zone_map ? _segment_zone_map->ByteSizeLong() : 0);
323
11.2k
}
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.2k
void ColumnReader::check_data_by_zone_map_for_test(const MutableColumnPtr& dst) const {
330
20.2k
    if (!_segment_zone_map) {
331
1.87k
        return;
332
1.87k
    }
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.08k
                                         const ColumnIteratorOptions& iter_opts) {
642
9.08k
    if (!_ordinal_index) {
643
0
        return Status::InternalError("ordinal_index not inited");
644
0
    }
645
9.08k
    return _ordinal_index->load(use_page_cache, kept_in_memory, iter_opts.stats, &iter_opts.io_ctx);
646
9.08k
}
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 (field_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.01k
                                       const ColumnIteratorOptions& iter_opts) {
779
9.01k
    RETURN_IF_ERROR(_load_ordinal_index(_use_index_page_cache, _opts.kept_in_memory, iter_opts));
780
9.01k
    *iter = _ordinal_index->seek_at_or_before(ordinal);
781
9.01k
    if (!iter->valid()) {
782
0
        return Status::NotFound("Failed to seek to ordinal {}, ", ordinal);
783
0
    }
784
9.01k
    return Status::OK();
785
9.01k
}
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.69k
Status ColumnReader::new_iterator(ColumnIteratorUPtr* iterator, const TabletColumn* tablet_column) {
798
1.69k
    return new_iterator(iterator, tablet_column, nullptr);
799
1.69k
}
800
801
Status ColumnReader::new_iterator(ColumnIteratorUPtr* iterator, const TabletColumn* tablet_column,
802
8.81k
                                  const StorageReadOptions* opt) {
803
8.81k
    if (is_empty()) {
804
138
        *iterator = std::make_unique<EmptyFileColumnIterator>();
805
138
        return Status::OK();
806
138
    }
807
8.67k
    if (is_scalar_type(_meta_type)) {
808
8.37k
        if (is_string_type(_meta_type)) {
809
2.89k
            *iterator = std::make_unique<StringFileColumnIterator>(shared_from_this());
810
5.48k
        } else {
811
5.48k
            *iterator = std::make_unique<FileColumnIterator>(shared_from_this());
812
5.48k
        }
813
8.37k
        (*iterator)->set_column_name(tablet_column ? tablet_column->name() : "");
814
8.37k
        return Status::OK();
815
8.37k
    } else {
816
300
        auto type = _meta_type;
817
300
        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
270
        case FieldType::OLAP_FIELD_TYPE_MAP: {
828
270
            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
300
        }
834
300
    }
835
8.67k
}
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
270
                                      const TabletColumn* tablet_column) {
870
270
    ColumnIteratorUPtr key_iterator;
871
270
    RETURN_IF_ERROR(_sub_readers[0]->new_iterator(
872
270
            &key_iterator, tablet_column && tablet_column->get_subtype_count() > 1
873
270
                                   ? &tablet_column->get_sub_column(0)
874
270
                                   : nullptr));
875
270
    key_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(0).name() : "");
876
270
    ColumnIteratorUPtr val_iterator;
877
270
    RETURN_IF_ERROR(_sub_readers[1]->new_iterator(
878
270
            &val_iterator, tablet_column && tablet_column->get_subtype_count() > 1
879
270
                                   ? &tablet_column->get_sub_column(1)
880
270
                                   : nullptr));
881
270
    val_iterator->set_column_name(tablet_column ? tablet_column->get_sub_column(1).name() : "");
882
270
    ColumnIteratorUPtr offsets_iterator;
883
270
    RETURN_IF_ERROR(_sub_readers[2]->new_iterator(&offsets_iterator, nullptr));
884
270
    auto* file_iter = static_cast<FileColumnIterator*>(offsets_iterator.release());
885
270
    OffsetFileColumnIteratorUPtr ofcIter = std::make_unique<OffsetFileColumnIterator>(
886
270
            std::unique_ptr<FileColumnIterator>(file_iter));
887
888
270
    ColumnIteratorUPtr null_iterator;
889
270
    if (is_nullable()) {
890
0
        RETURN_IF_ERROR(_sub_readers[3]->new_iterator(&null_iterator, nullptr));
891
0
    }
892
270
    *iterator = std::make_unique<MapFileColumnIterator>(
893
270
            shared_from_this(), std::move(null_iterator), std::move(ofcIter),
894
270
            std::move(key_iterator), std::move(val_iterator));
895
270
    return Status::OK();
896
270
}
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.0k
void ColumnIterator::_recovery_from_place_holder_column(MutableColumnPtr& dst) {
948
24.0k
    if (_read_phase == ReadPhase::LAZY && _has_place_holder_column) {
949
3
        dst->clear();
950
3
        _has_place_holder_column = false;
951
3
    }
952
24.0k
}
953
954
Result<TColumnAccessPaths> ColumnIterator::_get_sub_access_paths(
955
187
        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
346
    for (auto it = sub_access_paths.begin(); it != sub_access_paths.end();) {
967
164
        TColumnAccessPath& name_path = *it;
968
164
        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
162
        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
159
        name_path.data_access_path.path.erase(name_path.data_access_path.path.begin());
980
159
        if (!name_path.data_access_path.path.empty()) {
981
133
            ++it;
982
133
        } 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
159
    }
991
182
    return sub_access_paths;
992
187
}
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
305
        : _map_reader(reader),
1001
305
          _offsets_iterator(std::move(offsets_iterator)),
1002
305
          _key_iterator(std::move(key_iterator)),
1003
305
          _val_iterator(std::move(val_iterator)) {
1004
305
    if (_map_reader->is_nullable()) {
1005
2
        _null_iterator = std::move(null_iterator);
1006
2
    }
1007
305
}
1008
1009
266
Status MapFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1010
266
    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
266
    RETURN_IF_ERROR(_key_iterator->init(opts));
1015
266
    RETURN_IF_ERROR(_val_iterator->init(opts));
1016
266
    RETURN_IF_ERROR(_offsets_iterator->init(opts));
1017
266
    if (_map_reader->is_nullable()) {
1018
0
        RETURN_IF_ERROR(_null_iterator->init(opts));
1019
0
    }
1020
266
    return Status::OK();
1021
266
}
1022
1023
254
Status MapFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
1024
254
    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
254
    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
254
    if (_map_reader->is_nullable()) {
1038
0
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1039
0
    }
1040
254
    RETURN_IF_ERROR(_offsets_iterator->seek_to_ordinal(ord));
1041
254
    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
254
    ordinal_t offset = 0;
1047
254
    RETURN_IF_ERROR(_offsets_iterator->_peek_one_offset(&offset));
1048
254
    RETURN_IF_ERROR(_key_iterator->seek_to_ordinal(offset));
1049
254
    RETURN_IF_ERROR(_val_iterator->seek_to_ordinal(offset));
1050
254
    return Status::OK();
1051
254
}
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
254
Status MapFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1089
254
    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
254
    _recovery_from_place_holder_column(dst);
1096
1097
254
    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
253
    auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
1122
253
            is_column_nullable(*dst) ? static_cast<ColumnNullable&>(*dst).get_nested_column()
1123
253
                                     : *dst);
1124
253
    const bool read_meta_columns = need_to_read_meta_columns();
1125
253
    MutableColumnPtr column_offsets_ptr;
1126
253
    if (read_meta_columns) {
1127
253
        column_offsets_ptr = IColumn::mutate(std::move(column_map.get_offsets_ptr()));
1128
253
    } 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
253
    Defer defer_offsets {[&] {
1144
253
        if (read_meta_columns) {
1145
253
            auto typed_column_offsets_ptr = ColumnMap::COffsets::cast_to_column_mutptr(
1146
253
                    assert_cast<ColumnMap::COffsets*, TypeCheckOnRelease::DISABLE>(
1147
253
                            column_offsets_ptr.get()));
1148
253
            column_offsets_ptr = nullptr;
1149
253
            column_map.get_offsets_ptr() = std::move(typed_column_offsets_ptr);
1150
253
        }
1151
253
    }};
1152
253
    bool offsets_has_null = false;
1153
253
    ssize_t start = column_offsets_ptr->size();
1154
253
    RETURN_IF_ERROR(_offsets_iterator->next_batch(n, column_offsets_ptr, &offsets_has_null));
1155
253
    if (*n == 0) {
1156
0
        return Status::OK();
1157
0
    }
1158
253
    auto& column_offsets = static_cast<ColumnArray::ColumnOffsets&>(*column_offsets_ptr);
1159
253
    RETURN_IF_ERROR(_offsets_iterator->_calculate_offsets(start, column_offsets));
1160
253
    DCHECK(column_offsets.get_data().back() >= column_offsets.get_data()[start - 1]);
1161
253
    size_t num_items =
1162
253
            column_offsets.get_data().back() - column_offsets.get_data()[start - 1]; // -1 is valid
1163
1164
253
    if (num_items > 0) {
1165
200
        auto key_ptr = IColumn::mutate(std::move(column_map.get_keys_ptr()));
1166
200
        auto val_ptr = IColumn::mutate(std::move(column_map.get_values_ptr()));
1167
200
        Defer defer_keys {[&] { column_map.get_keys_ptr() = std::move(key_ptr); }};
1168
200
        Defer defer_values {[&] { column_map.get_values_ptr() = std::move(val_ptr); }};
1169
200
        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
200
        } else {
1174
200
            auto read_or_fill_child = [&](ColumnIterator* iterator,
1175
400
                                          MutableColumnPtr& column) -> Status {
1176
400
                if (_read_phase == ReadPhase::LAZY && read_meta_columns &&
1177
400
                    iterator->read_requirement() == ReadRequirement::SKIP) {
1178
0
                    column->insert_many_defaults(num_items);
1179
0
                    return Status::OK();
1180
0
                }
1181
1182
400
                bool dummy_has_null = false;
1183
400
                size_t num_read = num_items;
1184
400
                RETURN_IF_ERROR(iterator->next_batch(&num_read, column, &dummy_has_null));
1185
400
                DCHECK(num_read == num_items);
1186
400
                return Status::OK();
1187
400
            };
1188
200
            RETURN_IF_ERROR(read_or_fill_child(_key_iterator.get(), key_ptr));
1189
200
            RETURN_IF_ERROR(read_or_fill_child(_val_iterator.get(), val_ptr));
1190
200
        }
1191
200
    }
1192
1193
253
    if (is_column_nullable(*dst) && read_meta_columns) {
1194
0
        size_t num_read = *n;
1195
0
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1196
        // in not-null to null linked-schemachange mode,
1197
        // actually we do not change dat data include meta in footer,
1198
        // so may dst from changed meta which is nullable but old data is not nullable,
1199
        // if so, we should set null_map to all null by default
1200
0
        if (_null_iterator) {
1201
0
            bool null_signs_has_null = false;
1202
0
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
1203
0
            RETURN_IF_ERROR(
1204
0
                    _null_iterator->next_batch(&num_read, null_map_column, &null_signs_has_null));
1205
0
        } else {
1206
0
            null_map_ptr->insert_many_vals(0, num_read);
1207
0
        }
1208
0
        DCHECK(num_read == *n);
1209
0
    }
1210
253
    return Status::OK();
1211
253
}
1212
1213
Status MapFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
1214
20
                                             MutableColumnPtr& dst) {
1215
20
    if (!need_to_read()) {
1216
1
        DLOG(INFO) << "Map column iterator column " << _column_name << " skip reading.";
1217
1
        _convert_to_place_holder_column(dst, count);
1218
1
        return Status::OK();
1219
1
    }
1220
1221
19
    _recovery_from_place_holder_column(dst);
1222
1223
19
    if (read_null_map_only()) {
1224
        // NULL_MAP_ONLY mode: read null map by rowids, fill nested ColumnMap with empty defaults
1225
1
        DORIS_CHECK(is_column_nullable(*dst));
1226
1
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
1227
1
        if (_null_iterator) {
1228
1
            auto null_map_ptr = nullable_col.get_null_map_column_ptr();
1229
1
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
1230
1
            RETURN_IF_ERROR(_null_iterator->read_by_rowids(rowids, count, null_map_column));
1231
1
        } else {
1232
            // schema-change: column became nullable but old segment has no null data
1233
0
            auto null_map_ptr = nullable_col.get_null_map_column_ptr();
1234
0
            null_map_ptr->insert_many_vals(0, count);
1235
0
        }
1236
        // fill nested ColumnMap with empty (zero-element) maps
1237
1
        auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
1238
1
                nullable_col.get_nested_column());
1239
1
        column_map.insert_many_defaults(count);
1240
1
        return Status::OK();
1241
1
    }
1242
1243
18
    if (count == 0) {
1244
0
        return Status::OK();
1245
0
    }
1246
1247
    // resolve ColumnMap and nullable wrapper
1248
18
    auto& column_map = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
1249
18
            is_column_nullable(*dst) ? static_cast<ColumnNullable&>(*dst).get_nested_column()
1250
18
                                     : *dst);
1251
18
    const bool read_meta_columns = need_to_read_meta_columns();
1252
18
    MutableColumnPtr offsets_ptr;
1253
18
    if (read_meta_columns) {
1254
17
        offsets_ptr = IColumn::mutate(std::move(column_map.get_offsets_ptr()));
1255
17
    } else {
1256
1
        const auto base_offset =
1257
1
                column_map.get_offsets().empty() ? 0 : column_map.get_offsets().back();
1258
1
        offsets_ptr = ColumnMap::COffsets::create();
1259
1
        assert_cast<ColumnOffset64&, TypeCheckOnRelease::DISABLE>(*offsets_ptr)
1260
1
                .insert_value(base_offset);
1261
1
    }
1262
18
    Defer defer_offsets {[&] {
1263
18
        if (read_meta_columns) {
1264
17
            auto typed_offsets_ptr = ColumnMap::COffsets::cast_to_column_mutptr(
1265
17
                    assert_cast<ColumnMap::COffsets*, TypeCheckOnRelease::DISABLE>(
1266
17
                            offsets_ptr.get()));
1267
17
            offsets_ptr = nullptr;
1268
17
            column_map.get_offsets_ptr() = std::move(typed_offsets_ptr);
1269
17
        }
1270
18
    }};
1271
18
    auto& offsets = static_cast<ColumnArray::ColumnOffsets&>(*offsets_ptr);
1272
18
    size_t base = offsets.get_data().empty() ? 0 : offsets.get_data().back();
1273
1274
    // 1. bulk read null-map if nullable
1275
18
    std::vector<uint8_t> null_mask; // 0: not null, 1: null
1276
18
    if (read_meta_columns) {
1277
17
        if (_map_reader->is_nullable()) {
1278
            // For nullable map columns, the destination column must also be nullable.
1279
0
            if (UNLIKELY(!is_column_nullable(*dst))) {
1280
0
                return Status::InternalError(
1281
0
                        "unexpected non-nullable destination column for nullable map reader");
1282
0
            }
1283
0
            MutableColumnPtr null_map_ptr =
1284
0
                    static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1285
0
            size_t null_before = null_map_ptr->size();
1286
0
            RETURN_IF_ERROR(_null_iterator->read_by_rowids(rowids, count, null_map_ptr));
1287
            // extract a light-weight view to decide element reads
1288
0
            auto& null_map_col = assert_cast<ColumnUInt8&>(*null_map_ptr);
1289
0
            const auto* src = null_map_col.get_data().data() + null_before;
1290
0
            null_mask.assign(src, src + count);
1291
17
        } else if (is_column_nullable(*dst)) {
1292
            // in not-null to null linked-schemachange mode,
1293
            // actually we do not change dat data include meta in footer,
1294
            // so may dst from changed meta which is nullable but old data is not nullable,
1295
            // if so, we should set null_map to all null by default
1296
0
            MutableColumnPtr null_map_ptr =
1297
0
                    static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1298
0
            auto& null_map = assert_cast<ColumnUInt8&>(*null_map_ptr);
1299
0
            null_map.insert_many_vals(0, count);
1300
0
        }
1301
17
    } else if (_map_reader->is_nullable()) {
1302
        // In lazy mode the parent null map has already been materialized during
1303
        // predicate read and filtered together with the block. Reuse that dst
1304
        // null map to avoid re-reading the same meta column from storage.
1305
0
        if (UNLIKELY(!is_column_nullable(*dst))) {
1306
0
            return Status::InternalError(
1307
0
                    "unexpected non-nullable destination column for nullable map reader");
1308
0
        }
1309
0
        const auto& null_map_col = static_cast<const ColumnNullable&>(*dst).get_null_map_column();
1310
0
        DORIS_CHECK(null_map_col.size() == count);
1311
0
        const auto* src = null_map_col.get_data().data();
1312
0
        null_mask.assign(src, src + count);
1313
0
    }
1314
1315
    // 2. Bulk read source start ordinals for requested rows. The offsets stored
1316
    // in dst already describe the filtered output shape when read_meta_columns is
1317
    // false, but they do not contain the source key/value ordinal for each
1318
    // selected rowid. We still need the storage offsets here to seek child
1319
    // iterators to the correct source element ranges.
1320
18
    MutableColumnPtr starts_col = ColumnOffset64::create();
1321
18
    starts_col->reserve(count);
1322
18
    RETURN_IF_ERROR(_offsets_iterator->read_by_rowids(rowids, count, starts_col));
1323
1324
    // 3. bulk read next-start ordinals for rowid+1 (within bounds)
1325
18
    std::vector<rowid_t> next_rowids(count);
1326
2.32k
    for (size_t i = 0; i < count; ++i) {
1327
2.30k
        uint64_t nr = rowids[i] + 1;
1328
2.30k
        next_rowids[i] = nr < _map_reader->num_rows() ? static_cast<rowid_t>(nr)
1329
2.30k
                                                      : static_cast<rowid_t>(0); // placeholder
1330
2.30k
    }
1331
18
    MutableColumnPtr next_starts_col = ColumnOffset64::create();
1332
18
    next_starts_col->reserve(count);
1333
    // read for all; we'll fix out-of-bound cases below
1334
18
    RETURN_IF_ERROR(_offsets_iterator->read_by_rowids(next_rowids.data(), count, next_starts_col));
1335
1336
    // 4. fix next_start for rows whose next_rowid is out-of-bound (rowid == num_rows-1)
1337
2.32k
    for (size_t i = 0; i < count; ++i) {
1338
2.30k
        if (rowids[i] + 1 >= _map_reader->num_rows()) {
1339
            // seek to the last row and consume one to move decoder to end-of-page,
1340
            // then peek page-tail sentinel next_array_item_ordinal as next_start
1341
13
            RETURN_IF_ERROR(_offsets_iterator->seek_to_ordinal(rowids[i]));
1342
13
            size_t one = 1;
1343
13
            bool has_null_unused = false;
1344
13
            MutableColumnPtr tmp = ColumnOffset64::create();
1345
13
            RETURN_IF_ERROR(_offsets_iterator->next_batch(&one, tmp, &has_null_unused));
1346
13
            ordinal_t ns = 0;
1347
13
            RETURN_IF_ERROR(_offsets_iterator->_peek_one_offset(&ns));
1348
            // overwrite with sentinel
1349
13
            assert_cast<ColumnOffset64&, TypeCheckOnRelease::DISABLE>(*next_starts_col)
1350
13
                    .get_data()[i] = ns;
1351
13
        }
1352
2.30k
    }
1353
1354
    // 5. compute sizes and append offsets prefix-sum
1355
18
    auto& starts_data = assert_cast<ColumnOffset64&>(*starts_col).get_data();
1356
18
    auto& next_starts_data = assert_cast<ColumnOffset64&>(*next_starts_col).get_data();
1357
18
    std::vector<size_t> sizes(count, 0);
1358
18
    size_t acc = base;
1359
18
    if (read_meta_columns) {
1360
17
        offsets.get_data().reserve(offsets.get_data().size() + count);
1361
17
    }
1362
2.32k
    for (size_t i = 0; i < count; ++i) {
1363
2.30k
        auto sz = static_cast<size_t>(next_starts_data[i] - starts_data[i]);
1364
2.30k
        if (_map_reader->is_nullable() && !null_mask.empty() && null_mask[i]) {
1365
0
            sz = 0; // null rows do not consume elements
1366
0
        }
1367
2.30k
        sizes[i] = sz;
1368
2.30k
        acc += sz;
1369
2.30k
        if (read_meta_columns) {
1370
2.30k
            offsets.get_data().push_back(acc);
1371
2.30k
        }
1372
2.30k
    }
1373
1374
    // 6. read key/value elements for non-empty sizes
1375
18
    auto keys_ptr = IColumn::mutate(std::move(column_map.get_keys_ptr()));
1376
18
    auto vals_ptr = IColumn::mutate(std::move(column_map.get_values_ptr()));
1377
18
    Defer defer_keys {[&] { column_map.get_keys_ptr() = std::move(keys_ptr); }};
1378
18
    Defer defer_values {[&] { column_map.get_values_ptr() = std::move(vals_ptr); }};
1379
    // In lazy phase with read_meta_columns=true, this map was only a placeholder during
1380
    // predicate evaluation and is cleared before the lazy read. If only KEYS or VALUES is
1381
    // requested, fill the skipped counterpart with defaults to keep ColumnMap's
1382
    // key/value/offset sizes consistent without reading unnecessary data pages.
1383
18
    const bool fill_lazy_skipped_keys = _read_phase == ReadPhase::LAZY && read_meta_columns &&
1384
18
                                        _key_iterator->read_requirement() == ReadRequirement::SKIP;
1385
18
    const bool fill_lazy_skipped_values =
1386
18
            _read_phase == ReadPhase::LAZY && read_meta_columns &&
1387
18
            _val_iterator->read_requirement() == ReadRequirement::SKIP;
1388
18
    auto read_or_fill_range = [&](ColumnIterator* iterator, MutableColumnPtr& column,
1389
18
                                  ordinal_t start_idx, size_t num_items,
1390
364
                                  bool fill_lazy_skipped_child) -> Status {
1391
364
        if (num_items == 0) {
1392
24
            return Status::OK();
1393
24
        }
1394
340
        if (fill_lazy_skipped_child) {
1395
1
            column->insert_many_defaults(num_items);
1396
1
            return Status::OK();
1397
1
        }
1398
339
        if (_read_phase == ReadPhase::LAZY && !iterator->need_to_read()) {
1399
1
            return Status::OK();
1400
1
        }
1401
338
        size_t n = num_items;
1402
338
        bool dummy_has_null = false;
1403
338
        RETURN_IF_ERROR(iterator->seek_to_ordinal(start_idx));
1404
338
        RETURN_IF_ERROR(iterator->next_batch(&n, column, &dummy_has_null));
1405
338
        DCHECK(n == num_items);
1406
338
        return Status::OK();
1407
338
    };
1408
1409
18
    size_t this_run = sizes[0];
1410
18
    auto start_idx = starts_data[0];
1411
18
    auto last_idx = starts_data[0] + this_run;
1412
2.30k
    for (size_t i = 1; i < count; ++i) {
1413
2.28k
        size_t sz = sizes[i];
1414
2.28k
        if (sz == 0) {
1415
954
            continue;
1416
954
        }
1417
1.33k
        auto start = static_cast<ordinal_t>(starts_data[i]);
1418
1.33k
        if (start != last_idx) {
1419
164
            RETURN_IF_ERROR(read_or_fill_range(_key_iterator.get(), keys_ptr, start_idx, this_run,
1420
164
                                               fill_lazy_skipped_keys));
1421
164
            RETURN_IF_ERROR(read_or_fill_range(_val_iterator.get(), vals_ptr, start_idx, this_run,
1422
164
                                               fill_lazy_skipped_values));
1423
164
            start_idx = start;
1424
164
            this_run = sz;
1425
164
            last_idx = start + sz;
1426
164
            continue;
1427
164
        }
1428
1429
1.16k
        this_run += sz;
1430
1.16k
        last_idx += sz;
1431
1.16k
    }
1432
1433
18
    RETURN_IF_ERROR(read_or_fill_range(_key_iterator.get(), keys_ptr, start_idx, this_run,
1434
18
                                       fill_lazy_skipped_keys));
1435
18
    RETURN_IF_ERROR(read_or_fill_range(_val_iterator.get(), vals_ptr, start_idx, this_run,
1436
18
                                       fill_lazy_skipped_values));
1437
18
    return Status::OK();
1438
18
}
1439
1440
7
void MapFileColumnIterator::set_lazy_output_requirement() {
1441
7
    set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1442
7
    _key_iterator->set_lazy_output_requirement();
1443
7
    _val_iterator->set_lazy_output_requirement();
1444
7
}
1445
1446
0
void MapFileColumnIterator::remove_pruned_sub_iterators() {
1447
0
    _key_iterator->remove_pruned_sub_iterators();
1448
0
    _val_iterator->remove_pruned_sub_iterators();
1449
0
}
1450
1451
Status MapFileColumnIterator::set_access_paths(const TColumnAccessPaths& all_access_paths,
1452
26
                                               const TColumnAccessPaths& predicate_access_paths) {
1453
26
    if (all_access_paths.empty() && predicate_access_paths.empty()) {
1454
0
        return Status::OK();
1455
0
    }
1456
1457
26
    const auto requirement_before_access_path = _read_requirement;
1458
26
    if (!predicate_access_paths.empty()) {
1459
18
        set_read_requirement_self(ReadRequirement::PREDICATE);
1460
18
        DLOG(INFO) << "Map column iterator set sub-column " << _column_name << " to PREDICATE";
1461
18
    }
1462
1463
26
    const bool has_current_level_data_path =
1464
26
            std::ranges::any_of(all_access_paths, [this](const TColumnAccessPath& path) {
1465
26
                return is_current_level_data_access_path(path, _column_name);
1466
26
            });
1467
26
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
1468
25
    auto sub_predicate_access_paths =
1469
25
            DORIS_TRY(_get_sub_access_paths(predicate_access_paths, true));
1470
25
    if (has_current_level_data_path) {
1471
6
        remove_current_level_meta_access_paths(sub_all_access_paths);
1472
6
    }
1473
25
    const bool has_current_level_predicate_meta_path =
1474
25
            std::ranges::any_of(sub_predicate_access_paths, is_current_level_meta_access_path);
1475
    // Current-level predicate metadata paths are consumed by this map iterator and must not be
1476
    // forwarded to key/value children. The FE keeps all_access_paths as a superset of predicate
1477
    // paths, so meta-only mode is still decided from sub_all_access_paths below.
1478
25
    remove_current_level_meta_access_paths(sub_predicate_access_paths);
1479
1480
25
    if (sub_predicate_access_paths.empty() && _read_requirement == ReadRequirement::PREDICATE &&
1481
25
        !has_current_level_predicate_meta_path) {
1482
        // if no sub-column in predicate_access_paths, but current column is PREDICATE,
1483
        // then we should set key/value iterator to PREDICATE too.
1484
1
        _key_iterator->set_read_requirement(ReadRequirement::PREDICATE);
1485
1
        _val_iterator->set_read_requirement(ReadRequirement::PREDICATE);
1486
1
    }
1487
1488
25
    if (sub_predicate_access_paths.empty()) {
1489
        // Check for meta-only modes (OFFSET_ONLY or NULL_MAP_ONLY). Only skip key/value
1490
        // iterators when no predicate sub-path needs them in the predicate phase.
1491
10
        _check_and_set_meta_read_mode(requirement_before_access_path, sub_all_access_paths);
1492
10
        if (read_offset_only()) {
1493
0
            _key_iterator->set_read_requirement(ReadRequirement::SKIP);
1494
0
            _val_iterator->set_read_requirement(ReadRequirement::SKIP);
1495
0
            DLOG(INFO) << "Map column iterator set column " << _column_name
1496
0
                       << " to OFFSET_ONLY meta read mode, key/value columns set to SKIP";
1497
0
            return Status::OK();
1498
0
        }
1499
10
        if (read_null_map_only()) {
1500
2
            _key_iterator->set_read_requirement(ReadRequirement::SKIP);
1501
2
            _val_iterator->set_read_requirement(ReadRequirement::SKIP);
1502
2
            DLOG(INFO) << "Map column iterator set column " << _column_name
1503
2
                       << " to NULL_MAP_ONLY meta read mode, key/value columns set to SKIP";
1504
2
            return Status::OK();
1505
2
        }
1506
10
    }
1507
1508
    // A current-level data path is consumed by _get_sub_access_paths() and leaves
1509
    // sub_all_access_paths empty after marking key/value as lazy-read targets. Predicate
1510
    // sub-paths still have to be routed to child iterators for the predicate phase.
1511
23
    if (sub_all_access_paths.empty() && sub_predicate_access_paths.empty()) {
1512
2
        return Status::OK();
1513
2
    }
1514
1515
21
    TColumnAccessPaths key_all_access_paths;
1516
21
    TColumnAccessPaths val_all_access_paths;
1517
21
    TColumnAccessPaths key_predicate_access_paths;
1518
21
    TColumnAccessPaths val_predicate_access_paths;
1519
1520
21
    for (auto paths : sub_all_access_paths) {
1521
18
        if (paths.data_access_path.path[0] == ACCESS_ALL) {
1522
            // ACCESS_ALL means element_at(map, key) style access: the key column must be
1523
            // fully read so that the runtime can match the requested key, while any sub-path
1524
            // qualifiers (e.g. OFFSET) apply only to the value column.
1525
            // For key: create a path with just the column name (= full data access).
1526
2
            TColumnAccessPath key_path;
1527
2
            key_path.__set_type(paths.type);
1528
2
            TDataAccessPath key_data_path;
1529
2
            key_data_path.__set_path({_key_iterator->column_name()});
1530
2
            key_path.__set_data_access_path(key_data_path);
1531
2
            key_all_access_paths.emplace_back(std::move(key_path));
1532
            // For value: pass the full sub-path so qualifiers like OFFSET propagate.
1533
2
            paths.data_access_path.path[0] = _val_iterator->column_name();
1534
2
            val_all_access_paths.emplace_back(paths);
1535
16
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_KEYS) {
1536
4
            paths.data_access_path.path[0] = _key_iterator->column_name();
1537
4
            key_all_access_paths.emplace_back(paths);
1538
12
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_VALUES) {
1539
10
            paths.data_access_path.path[0] = _val_iterator->column_name();
1540
10
            val_all_access_paths.emplace_back(paths);
1541
10
        }
1542
18
    }
1543
21
    for (auto paths : sub_predicate_access_paths) {
1544
16
        if (paths.data_access_path.path[0] == ACCESS_ALL) {
1545
            // Same logic as above: key needs full data, value gets the sub-path.
1546
1
            TColumnAccessPath key_path;
1547
1
            key_path.__set_type(paths.type);
1548
1
            TDataAccessPath key_data_path;
1549
1
            key_data_path.__set_path({_key_iterator->column_name()});
1550
1
            key_path.__set_data_access_path(key_data_path);
1551
1
            key_predicate_access_paths.emplace_back(std::move(key_path));
1552
1
            paths.data_access_path.path[0] = _val_iterator->column_name();
1553
1
            val_predicate_access_paths.emplace_back(paths);
1554
15
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_KEYS) {
1555
4
            paths.data_access_path.path[0] = _key_iterator->column_name();
1556
4
            key_predicate_access_paths.emplace_back(paths);
1557
11
        } else if (paths.data_access_path.path[0] == ACCESS_MAP_VALUES) {
1558
11
            paths.data_access_path.path[0] = _val_iterator->column_name();
1559
11
            val_predicate_access_paths.emplace_back(paths);
1560
11
        }
1561
16
    }
1562
1563
21
    const auto need_read_keys =
1564
21
            !key_all_access_paths.empty() || !key_predicate_access_paths.empty();
1565
21
    const auto need_read_values =
1566
21
            !val_all_access_paths.empty() || !val_predicate_access_paths.empty();
1567
1568
21
    if (need_read_keys) {
1569
10
        RETURN_IF_ERROR(
1570
10
                _key_iterator->set_access_paths(key_all_access_paths, key_predicate_access_paths));
1571
        // Apply LAZY_OUTPUT after child predicate paths have been handled. Read requirements are
1572
        // monotonic, so a predicate-only child already promoted to PREDICATE will not
1573
        // be downgraded, while a non-predicate child becomes a lazy materialization target.
1574
10
        _key_iterator->set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1575
11
    } else {
1576
11
        _key_iterator->set_read_requirement(ReadRequirement::SKIP);
1577
11
        DLOG(INFO) << "Map column iterator set key column to SKIP";
1578
11
    }
1579
1580
21
    if (need_read_values) {
1581
17
        RETURN_IF_ERROR(
1582
17
                _val_iterator->set_access_paths(val_all_access_paths, val_predicate_access_paths));
1583
        // Same as keys: predicate-only value paths stay PREDICATE because this
1584
        // post-processing update cannot lower a stronger child requirement.
1585
17
        _val_iterator->set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1586
17
    } else {
1587
4
        _val_iterator->set_read_requirement(ReadRequirement::SKIP);
1588
4
        DLOG(INFO) << "Map column iterator set value column to SKIP";
1589
4
    }
1590
21
    return Status::OK();
1591
21
}
1592
1593
14
void MapFileColumnIterator::set_read_phase(ReadPhase mode) {
1594
14
    ColumnIterator::set_read_phase(mode);
1595
14
    _key_iterator->set_read_phase(mode);
1596
14
    _val_iterator->set_read_phase(mode);
1597
14
}
1598
1599
0
void MapFileColumnIterator::finalize_lazy_phase(MutableColumnPtr& dst) {
1600
0
    _recovery_from_place_holder_column(dst);
1601
0
    auto& map_column = assert_cast<ColumnMap&, TypeCheckOnRelease::DISABLE>(
1602
0
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
1603
0
    auto keys_ptr = IColumn::mutate(std::move(map_column.get_keys_ptr()));
1604
0
    auto vals_ptr = IColumn::mutate(std::move(map_column.get_values_ptr()));
1605
0
    _key_iterator->finalize_lazy_phase(keys_ptr);
1606
0
    _val_iterator->finalize_lazy_phase(vals_ptr);
1607
0
    map_column.get_keys_ptr() = std::move(keys_ptr);
1608
0
    map_column.get_values_ptr() = std::move(vals_ptr);
1609
0
}
1610
1611
7
void MapFileColumnIterator::set_read_requirement(ReadRequirement requirement) {
1612
7
    set_read_requirement_self(requirement);
1613
7
    _key_iterator->set_read_requirement(requirement);
1614
7
    _val_iterator->set_read_requirement(requirement);
1615
7
}
1616
1617
21
bool MapFileColumnIterator::has_lazy_read_target() const {
1618
21
    return _read_requirement == ReadRequirement::LAZY_OUTPUT ||
1619
21
           _key_iterator->has_lazy_read_target() || _val_iterator->has_lazy_read_target();
1620
21
}
1621
1622
////////////////////////////////////////////////////////////////////////////////
1623
1624
StructFileColumnIterator::StructFileColumnIterator(
1625
        std::shared_ptr<ColumnReader> reader, ColumnIteratorUPtr null_iterator,
1626
        std::vector<ColumnIteratorUPtr>&& sub_column_iterators)
1627
58
        : _struct_reader(reader), _sub_column_iterators(std::move(sub_column_iterators)) {
1628
58
    if (_struct_reader->is_nullable()) {
1629
2
        _null_iterator = std::move(null_iterator);
1630
2
    }
1631
58
}
1632
1633
0
Status StructFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1634
0
    if (_read_requirement == ReadRequirement::SKIP) {
1635
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1636
0
        return Status::OK();
1637
0
    }
1638
1639
0
    for (auto& column_iterator : _sub_column_iterators) {
1640
0
        RETURN_IF_ERROR(column_iterator->init(opts));
1641
0
    }
1642
0
    if (_struct_reader->is_nullable()) {
1643
0
        RETURN_IF_ERROR(_null_iterator->init(opts));
1644
0
    }
1645
0
    return Status::OK();
1646
0
}
1647
1648
4
Status StructFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1649
4
    if (!need_to_read()) {
1650
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1651
0
        _convert_to_place_holder_column(dst, *n);
1652
0
        return Status::OK();
1653
0
    }
1654
1655
4
    _recovery_from_place_holder_column(dst);
1656
1657
4
    if (read_null_map_only()) {
1658
        // NULL_MAP_ONLY mode: read null map, fill nested ColumnStruct with empty defaults
1659
1
        DORIS_CHECK(is_column_nullable(*dst));
1660
1
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
1661
1
        auto null_map_ptr = nullable_col.get_null_map_column_ptr();
1662
1
        size_t num_read = *n;
1663
1
        if (_null_iterator) {
1664
1
            bool null_signs_has_null = false;
1665
1
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
1666
1
            RETURN_IF_ERROR(
1667
1
                    _null_iterator->next_batch(&num_read, null_map_column, &null_signs_has_null));
1668
1
        } else {
1669
            // schema-change: column became nullable but old segment has no null data
1670
0
            null_map_ptr->insert_many_vals(0, num_read);
1671
0
        }
1672
1
        DCHECK(num_read == *n);
1673
        // fill nested ColumnStruct with defaults to maintain consistent column sizes
1674
1
        auto& column_struct = assert_cast<ColumnStruct&, TypeCheckOnRelease::DISABLE>(
1675
1
                nullable_col.get_nested_column());
1676
1
        column_struct.insert_many_defaults(num_read);
1677
1
        *has_null = true;
1678
1
        return Status::OK();
1679
1
    }
1680
1681
3
    auto& column_struct = assert_cast<ColumnStruct&, TypeCheckOnRelease::DISABLE>(
1682
3
            is_column_nullable(*dst) ? static_cast<ColumnNullable&>(*dst).get_nested_column()
1683
3
                                     : *dst);
1684
9
    for (size_t i = 0; i < column_struct.tuple_size(); i++) {
1685
6
        size_t num_read = *n;
1686
6
        auto sub_column_ptr = IColumn::mutate(std::move(column_struct.get_column_ptr(i)));
1687
6
        Defer defer_sub_column {
1688
6
                [&] { column_struct.get_column_ptr(i) = std::move(sub_column_ptr); }};
1689
6
        bool column_has_null = false;
1690
6
        RETURN_IF_ERROR(
1691
6
                _sub_column_iterators[i]->next_batch(&num_read, sub_column_ptr, &column_has_null));
1692
6
        DCHECK(num_read == *n);
1693
6
    }
1694
1695
3
    if (is_column_nullable(*dst) && need_to_read_meta_columns()) {
1696
0
        size_t num_read = *n;
1697
0
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
1698
        // in not-null to null linked-schemachange mode,
1699
        // actually we do not change dat data include meta in footer,
1700
        // so may dst from changed meta which is nullable but old data is not nullable,
1701
        // if so, we should set null_map to all null by default
1702
0
        if (_null_iterator) {
1703
0
            bool null_signs_has_null = false;
1704
0
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
1705
0
            RETURN_IF_ERROR(
1706
0
                    _null_iterator->next_batch(&num_read, null_map_column, &null_signs_has_null));
1707
0
        } else {
1708
0
            null_map_ptr->insert_many_vals(0, num_read);
1709
0
        }
1710
0
        DCHECK(num_read == *n);
1711
0
    }
1712
1713
3
    return Status::OK();
1714
3
}
1715
1716
2
Status StructFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
1717
2
    if (!need_to_read()) {
1718
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1719
0
        return Status::OK();
1720
0
    }
1721
1722
2
    if (read_null_map_only()) {
1723
        // In NULL_MAP_ONLY mode, only seek the null iterator; skip all sub-column iterators
1724
0
        if (_struct_reader->is_nullable() && _null_iterator) {
1725
0
            RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1726
0
        }
1727
0
        return Status::OK();
1728
0
    }
1729
1730
4
    for (auto& column_iterator : _sub_column_iterators) {
1731
4
        RETURN_IF_ERROR(column_iterator->seek_to_ordinal(ord));
1732
4
    }
1733
1734
2
    if (_struct_reader->is_nullable() && need_to_read_meta_columns()) {
1735
0
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
1736
0
    }
1737
2
    return Status::OK();
1738
2
}
1739
1740
0
Status StructFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
1741
0
    for (auto& column_iterator : _sub_column_iterators) {
1742
0
        RETURN_IF_ERROR(column_iterator->init_prefetcher(params));
1743
0
    }
1744
0
    if (_struct_reader->is_nullable()) {
1745
0
        RETURN_IF_ERROR(_null_iterator->init_prefetcher(params));
1746
0
    }
1747
0
    return Status::OK();
1748
0
}
1749
1750
void StructFileColumnIterator::collect_prefetchers(
1751
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
1752
2
        PrefetcherInitMethod init_method) {
1753
2
    if (!need_to_read()) {
1754
0
        return;
1755
0
    }
1756
2
    if (_struct_reader->is_nullable()) {
1757
2
        _null_iterator->collect_prefetchers(prefetchers, init_method);
1758
2
    }
1759
2
    if (read_null_map_only()) {
1760
0
        return;
1761
0
    }
1762
4
    for (auto& column_iterator : _sub_column_iterators) {
1763
4
        if (column_iterator->need_to_read()) {
1764
2
            column_iterator->collect_prefetchers(prefetchers, init_method);
1765
2
        }
1766
4
    }
1767
2
}
1768
1769
Status StructFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
1770
1
                                                MutableColumnPtr& dst) {
1771
1
    if (!need_to_read()) {
1772
0
        DLOG(INFO) << "Struct column iterator column " << _column_name << " skip reading.";
1773
0
        _convert_to_place_holder_column(dst, count);
1774
0
        return Status::OK();
1775
0
    }
1776
1777
1
    _recovery_from_place_holder_column(dst);
1778
1779
1
    if (count == 0) {
1780
0
        return Status::OK();
1781
0
    }
1782
1783
1
    size_t this_run = 1;
1784
1
    auto start_idx = rowids[0];
1785
1
    auto last_idx = rowids[0];
1786
5
    for (size_t i = 1; i < count; ++i) {
1787
4
        if (last_idx == rowids[i] - 1) {
1788
3
            last_idx = rowids[i];
1789
3
            this_run++;
1790
3
            continue;
1791
3
        }
1792
1
        RETURN_IF_ERROR(seek_to_ordinal(start_idx));
1793
1
        size_t num_read = this_run;
1794
1
        RETURN_IF_ERROR(next_batch(&num_read, dst));
1795
1
        DCHECK_EQ(num_read, this_run);
1796
1797
1
        start_idx = rowids[i];
1798
1
        last_idx = rowids[i];
1799
1
        this_run = 1;
1800
1
    }
1801
1802
1
    RETURN_IF_ERROR(seek_to_ordinal(start_idx));
1803
1
    size_t num_read = this_run;
1804
1
    RETURN_IF_ERROR(next_batch(&num_read, dst));
1805
1
    DCHECK_EQ(num_read, this_run);
1806
1
    return Status::OK();
1807
1
}
1808
1809
12
void StructFileColumnIterator::set_lazy_output_requirement() {
1810
12
    set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1811
24
    for (auto& sub_iterator : _sub_column_iterators) {
1812
24
        sub_iterator->set_lazy_output_requirement();
1813
24
    }
1814
12
}
1815
1816
4
void StructFileColumnIterator::remove_pruned_sub_iterators() {
1817
13
    for (auto it = _sub_column_iterators.begin(); it != _sub_column_iterators.end();) {
1818
9
        auto& sub_iterator = *it;
1819
9
        if (sub_iterator->read_requirement() == ReadRequirement::SKIP) {
1820
4
            DLOG(INFO) << "Struct column iterator remove pruned sub-column "
1821
4
                       << sub_iterator->column_name();
1822
4
            it = _sub_column_iterators.erase(it);
1823
5
        } else {
1824
5
            sub_iterator->remove_pruned_sub_iterators();
1825
5
            ++it;
1826
5
        }
1827
9
    }
1828
4
}
1829
1830
Status StructFileColumnIterator::set_access_paths(
1831
        const TColumnAccessPaths& all_access_paths,
1832
43
        const TColumnAccessPaths& predicate_access_paths) {
1833
43
    if (all_access_paths.empty() && predicate_access_paths.empty()) {
1834
1
        return Status::OK();
1835
1
    }
1836
1837
42
    const auto requirement_before_access_path = _read_requirement;
1838
42
    if (!predicate_access_paths.empty()) {
1839
31
        set_read_requirement_self(ReadRequirement::PREDICATE);
1840
31
        DLOG(INFO) << "Struct column iterator set sub-column " << _column_name << " to PREDICATE";
1841
31
    }
1842
1843
42
    const bool has_current_level_data_path =
1844
42
            std::ranges::any_of(all_access_paths, [this](const TColumnAccessPath& path) {
1845
36
                return is_current_level_data_access_path(path, _column_name);
1846
36
            });
1847
42
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
1848
38
    auto sub_predicate_access_paths =
1849
38
            DORIS_TRY(_get_sub_access_paths(predicate_access_paths, true));
1850
38
    if (has_current_level_data_path) {
1851
7
        remove_current_level_meta_access_paths(sub_all_access_paths);
1852
7
    }
1853
38
    const bool has_current_level_predicate_meta_path =
1854
38
            std::ranges::any_of(sub_predicate_access_paths, is_current_level_meta_access_path);
1855
    // Current-level predicate metadata paths are consumed by this struct iterator and must not be
1856
    // forwarded to child fields. The FE keeps all_access_paths as a superset of predicate paths, so
1857
    // NULL_MAP_ONLY is still decided from sub_all_access_paths below.
1858
38
    remove_current_level_meta_access_paths(sub_predicate_access_paths);
1859
1860
38
    if (sub_predicate_access_paths.empty()) {
1861
        // Check for NULL_MAP_ONLY mode: only read null map, skip all sub-columns.
1862
        // Do not take this early return when predicate child paths must still be read.
1863
15
        _check_and_set_meta_read_mode(requirement_before_access_path, sub_all_access_paths);
1864
15
        if (read_null_map_only()) {
1865
3
            for (auto& sub_iterator : _sub_column_iterators) {
1866
3
                sub_iterator->set_read_requirement(ReadRequirement::SKIP);
1867
3
            }
1868
2
            DLOG(INFO) << "Struct column iterator set column " << _column_name
1869
2
                       << " to NULL_MAP_ONLY meta read mode, all sub-columns set to SKIP";
1870
2
            return Status::OK();
1871
2
        }
1872
15
    }
1873
1874
36
    const auto no_sub_column_to_skip = sub_all_access_paths.empty();
1875
36
    const auto no_predicate_sub_column = sub_predicate_access_paths.empty();
1876
1877
72
    for (auto& sub_iterator : _sub_column_iterators) {
1878
72
        const auto name = sub_iterator->column_name();
1879
72
        TColumnAccessPaths sub_all_access_paths_of_this;
1880
72
        if (!no_sub_column_to_skip) {
1881
48
            for (const auto& paths : sub_all_access_paths) {
1882
48
                if (paths.data_access_path.path[0] == name) {
1883
24
                    sub_all_access_paths_of_this.emplace_back(paths);
1884
24
                }
1885
48
            }
1886
48
        }
1887
1888
72
        TColumnAccessPaths sub_predicate_access_paths_of_this;
1889
72
        if (!no_predicate_sub_column) {
1890
46
            for (const auto& paths : sub_predicate_access_paths) {
1891
46
                if (StringCaseEqual()(paths.data_access_path.path[0], name)) {
1892
23
                    sub_predicate_access_paths_of_this.emplace_back(paths);
1893
23
                }
1894
46
            }
1895
46
        }
1896
1897
        // Predicate-only child paths still need to be routed to the child iterator
1898
        // even when the child is not requested by ordinary projection access paths.
1899
72
        const bool need_to_read = no_sub_column_to_skip || !sub_all_access_paths_of_this.empty() ||
1900
72
                                  !sub_predicate_access_paths_of_this.empty();
1901
72
        if (!need_to_read) {
1902
23
            set_read_requirement_self(ReadRequirement::SKIP);
1903
23
            sub_iterator->set_read_requirement(ReadRequirement::SKIP);
1904
23
            DLOG(INFO) << "Struct column iterator set sub-column " << name << " to SKIP";
1905
23
            continue;
1906
23
        }
1907
1908
49
        if (no_predicate_sub_column && _read_requirement == ReadRequirement::PREDICATE &&
1909
49
            !has_current_level_predicate_meta_path) {
1910
            // if no sub-column in predicate_access_paths, but current column is PREDICATE,
1911
            // then we should set sub iterator to PREDICATE too.
1912
6
            sub_iterator->set_read_requirement(ReadRequirement::PREDICATE);
1913
6
        }
1914
1915
49
        RETURN_IF_ERROR(sub_iterator->set_access_paths(sub_all_access_paths_of_this,
1916
49
                                                       sub_predicate_access_paths_of_this));
1917
        // Set LAZY_OUTPUT after routing child predicate paths. If the child was needed only for
1918
        // predicate evaluation, set_access_paths() has already promoted it to
1919
        // PREDICATE and this monotonic update will not downgrade it. Otherwise, this
1920
        // marks the child as a lazy materialization target.
1921
48
        set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1922
48
        sub_iterator->set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
1923
48
    }
1924
35
    return Status::OK();
1925
36
}
1926
1927
24
void StructFileColumnIterator::set_read_phase(ReadPhase mode) {
1928
24
    ColumnIterator::set_read_phase(mode);
1929
46
    for (auto& sub_iterator : _sub_column_iterators) {
1930
46
        sub_iterator->set_read_phase(mode);
1931
46
    }
1932
24
}
1933
1934
1
void StructFileColumnIterator::finalize_lazy_phase(MutableColumnPtr& dst) {
1935
1
    _recovery_from_place_holder_column(dst);
1936
1
    auto& column_struct = assert_cast<ColumnStruct&, TypeCheckOnRelease::DISABLE>(
1937
1
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
1938
1939
2
    for (size_t i = 0; i < _sub_column_iterators.size(); ++i) {
1940
1
        auto& sub_column = column_struct.get_column_ptr(i);
1941
1
        MutableColumnPtr mutable_sub_column = IColumn::mutate(std::move(sub_column));
1942
1
        _sub_column_iterators[i]->finalize_lazy_phase(mutable_sub_column);
1943
1
        sub_column = std::move(mutable_sub_column);
1944
1
    }
1945
1
}
1946
1947
10
void StructFileColumnIterator::set_read_requirement(ReadRequirement requirement) {
1948
10
    set_read_requirement_self(requirement);
1949
20
    for (const auto& sub_column_iterator : _sub_column_iterators) {
1950
20
        sub_column_iterator->set_read_requirement(requirement);
1951
20
    }
1952
10
}
1953
1954
29
bool StructFileColumnIterator::has_lazy_read_target() const {
1955
29
    if (_read_requirement == ReadRequirement::LAZY_OUTPUT) {
1956
2
        return true;
1957
2
    }
1958
27
    return std::any_of(_sub_column_iterators.begin(), _sub_column_iterators.end(),
1959
52
                       [](const auto& sub_column_iterator) {
1960
52
                           return sub_column_iterator->has_lazy_read_target();
1961
52
                       });
1962
29
}
1963
1964
////////////////////////////////////////////////////////////////////////////////
1965
296
Status OffsetFileColumnIterator::init(const ColumnIteratorOptions& opts) {
1966
296
    RETURN_IF_ERROR(_offset_iterator->init(opts));
1967
    // allocate peek tmp column once
1968
296
    _peek_tmp_col = ColumnOffset64::create();
1969
296
    return Status::OK();
1970
296
}
1971
1972
295
Status OffsetFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
1973
295
    RETURN_IF_ERROR(_offset_iterator->next_batch(n, dst, has_null));
1974
295
    return Status::OK();
1975
295
}
1976
1977
582
Status OffsetFileColumnIterator::_peek_one_offset(ordinal_t* offset) {
1978
582
    if (_offset_iterator->get_current_page()->has_remaining()) {
1979
290
        PageDecoder* offset_page_decoder = _offset_iterator->get_current_page()->data_decoder.get();
1980
290
        size_t n = 1;
1981
290
        _peek_tmp_col->clear();
1982
290
        RETURN_IF_ERROR(offset_page_decoder->peek_next_batch(&n, _peek_tmp_col)); // not null
1983
290
        DCHECK(_peek_tmp_col->size() == 1);
1984
290
        *offset =
1985
290
                assert_cast<const ColumnOffset64*, TypeCheckOnRelease::DISABLE>(_peek_tmp_col.get())
1986
290
                        ->get_element(0);
1987
292
    } else {
1988
292
        *offset = _offset_iterator->get_current_page()->next_array_item_ordinal;
1989
292
    }
1990
582
    return Status::OK();
1991
582
}
1992
1993
0
Status OffsetFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
1994
0
    return _offset_iterator->init_prefetcher(params);
1995
0
}
1996
1997
void OffsetFileColumnIterator::collect_prefetchers(
1998
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
1999
2
        PrefetcherInitMethod init_method) {
2000
2
    _offset_iterator->collect_prefetchers(prefetchers, init_method);
2001
2
}
2002
2003
/**
2004
 *  first_storage_offset read from page should smaller than next_storage_offset which here call _peek_one_offset from page,
2005
    and first_column_offset is keep in memory data which is different dimension with (first_storage_offset and next_storage_offset)
2006
     eg. step1. read page: first_storage_offset = 16382
2007
         step2. read page below with _peek_one_offset(&last_offset): last_offset = 16387
2008
         step3. first_offset = 126 which is calculate in column offsets
2009
         for loop column offsets element in size
2010
            we can calculate from first_storage_offset to next_storage_offset one by one to fill with offsets_data in memory column offsets
2011
 * @param start
2012
 * @param column_offsets
2013
 * @return
2014
 */
2015
Status OffsetFileColumnIterator::_calculate_offsets(ssize_t start,
2016
283
                                                    ColumnArray::ColumnOffsets& column_offsets) {
2017
283
    ordinal_t next_storage_offset = 0;
2018
283
    RETURN_IF_ERROR(_peek_one_offset(&next_storage_offset));
2019
2020
    // calculate real offsets
2021
283
    auto& offsets_data = column_offsets.get_data();
2022
283
    ordinal_t first_column_offset = offsets_data[start - 1]; // -1 is valid
2023
283
    ordinal_t first_storage_offset = offsets_data[start];
2024
283
    DCHECK(next_storage_offset >= first_storage_offset);
2025
83.1k
    for (ssize_t i = start; i < offsets_data.size() - 1; ++i) {
2026
82.9k
        offsets_data[i] = first_column_offset + (offsets_data[i + 1] - first_storage_offset);
2027
82.9k
    }
2028
    // last offset
2029
283
    offsets_data[offsets_data.size() - 1] =
2030
283
            first_column_offset + (next_storage_offset - first_storage_offset);
2031
283
    return Status::OK();
2032
283
}
2033
2034
////////////////////////////////////////////////////////////////////////////////
2035
ArrayFileColumnIterator::ArrayFileColumnIterator(std::shared_ptr<ColumnReader> reader,
2036
                                                 OffsetFileColumnIteratorUPtr offset_reader,
2037
                                                 ColumnIteratorUPtr item_iterator,
2038
                                                 ColumnIteratorUPtr null_iterator)
2039
60
        : _array_reader(reader),
2040
60
          _offset_iterator(std::move(offset_reader)),
2041
60
          _item_iterator(std::move(item_iterator)) {
2042
60
    if (_array_reader->is_nullable()) {
2043
30
        _null_iterator = std::move(null_iterator);
2044
30
    }
2045
60
}
2046
2047
30
Status ArrayFileColumnIterator::init(const ColumnIteratorOptions& opts) {
2048
30
    if (_read_requirement == ReadRequirement::SKIP) {
2049
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
2050
0
        return Status::OK();
2051
0
    }
2052
2053
30
    RETURN_IF_ERROR(_offset_iterator->init(opts));
2054
30
    RETURN_IF_ERROR(_item_iterator->init(opts));
2055
30
    if (_array_reader->is_nullable()) {
2056
28
        RETURN_IF_ERROR(_null_iterator->init(opts));
2057
28
    }
2058
30
    return Status::OK();
2059
30
}
2060
2061
31
Status ArrayFileColumnIterator::_seek_by_offsets(ordinal_t ord) {
2062
31
    if (read_offset_only()) {
2063
        // In OFFSET_ONLY mode, item iterator is SKIP, no need to seek it
2064
0
        return Status::OK();
2065
0
    }
2066
    // using offsets info
2067
31
    ordinal_t offset = 0;
2068
31
    RETURN_IF_ERROR(_offset_iterator->_peek_one_offset(&offset));
2069
31
    RETURN_IF_ERROR(_item_iterator->seek_to_ordinal(offset));
2070
31
    return Status::OK();
2071
31
}
2072
2073
33
Status ArrayFileColumnIterator::seek_to_ordinal(ordinal_t ord) {
2074
33
    if (!need_to_read()) {
2075
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
2076
0
        return Status::OK();
2077
0
    }
2078
2079
33
    if (read_null_map_only()) {
2080
        // In NULL_MAP_ONLY mode, only seek the null iterator; skip offset and item iterators
2081
2
        if (_array_reader->is_nullable() && _null_iterator) {
2082
2
            RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
2083
2
        }
2084
2
        return Status::OK();
2085
2
    }
2086
2087
31
    RETURN_IF_ERROR(_offset_iterator->seek_to_ordinal(ord));
2088
31
    if (_array_reader->is_nullable()) {
2089
29
        RETURN_IF_ERROR(_null_iterator->seek_to_ordinal(ord));
2090
29
    }
2091
31
    return _seek_by_offsets(ord);
2092
31
}
2093
2094
32
Status ArrayFileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
2095
32
    if (!need_to_read()) {
2096
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading, read phase"
2097
0
                   << static_cast<int>(_read_phase)
2098
0
                   << ", read requirement: " << static_cast<int>(_read_requirement);
2099
0
        _convert_to_place_holder_column(dst, *n);
2100
0
        return Status::OK();
2101
0
    }
2102
2103
32
    _recovery_from_place_holder_column(dst);
2104
2105
32
    if (read_null_map_only()) {
2106
        // NULL_MAP_ONLY mode: read null map, fill nested ColumnArray with empty defaults
2107
3
        DORIS_CHECK(is_column_nullable(*dst));
2108
3
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
2109
3
        auto null_map_ptr = nullable_col.get_null_map_column_ptr();
2110
3
        size_t num_read = *n;
2111
3
        if (_null_iterator) {
2112
3
            bool null_signs_has_null = false;
2113
3
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
2114
3
            RETURN_IF_ERROR(
2115
3
                    _null_iterator->next_batch(&num_read, null_map_column, &null_signs_has_null));
2116
3
        } else {
2117
            // schema-change: column became nullable but old segment has no null data
2118
0
            null_map_ptr->insert_many_vals(0, num_read);
2119
0
        }
2120
3
        DCHECK(num_read == *n);
2121
        // fill nested ColumnArray with empty (zero-length) arrays
2122
3
        auto& column_array = assert_cast<ColumnArray&, TypeCheckOnRelease::DISABLE>(
2123
3
                nullable_col.get_nested_column());
2124
3
        column_array.insert_many_defaults(num_read);
2125
3
        *has_null = true;
2126
3
        return Status::OK();
2127
3
    }
2128
2129
29
    auto& column_array = assert_cast<ColumnArray&, TypeCheckOnRelease::DISABLE>(
2130
29
            is_column_nullable(*dst) ? static_cast<ColumnNullable&>(*dst).get_nested_column()
2131
29
                                     : *dst);
2132
2133
29
    bool offsets_has_null = false;
2134
29
    const bool read_meta_columns = need_to_read_meta_columns();
2135
29
    MutableColumnPtr column_offsets_ptr;
2136
29
    if (read_meta_columns) {
2137
29
        column_offsets_ptr = IColumn::mutate(std::move(column_array.get_offsets_ptr()));
2138
29
    } else {
2139
0
        const auto base_offset =
2140
0
                column_array.get_offsets().empty() ? 0 : column_array.get_offsets().back();
2141
0
        column_offsets_ptr = ColumnArray::ColumnOffsets::create();
2142
0
        assert_cast<ColumnOffset64&, TypeCheckOnRelease::DISABLE>(*column_offsets_ptr)
2143
0
                .insert_value(base_offset);
2144
0
    }
2145
29
    Defer defer_offsets {[&] {
2146
29
        if (read_meta_columns) {
2147
29
            auto typed_column_offsets_ptr = ColumnArray::ColumnOffsets::cast_to_column_mutptr(
2148
29
                    assert_cast<ColumnArray::ColumnOffsets*, TypeCheckOnRelease::DISABLE>(
2149
29
                            column_offsets_ptr.get()));
2150
29
            column_offsets_ptr = nullptr;
2151
29
            column_array.get_offsets_ptr() = std::move(typed_column_offsets_ptr);
2152
29
        }
2153
29
    }};
2154
29
    ssize_t start = column_offsets_ptr->size();
2155
29
    RETURN_IF_ERROR(_offset_iterator->next_batch(n, column_offsets_ptr, &offsets_has_null));
2156
29
    if (*n == 0) {
2157
0
        return Status::OK();
2158
0
    }
2159
29
    auto& column_offsets = static_cast<ColumnArray::ColumnOffsets&>(*column_offsets_ptr);
2160
29
    RETURN_IF_ERROR(_offset_iterator->_calculate_offsets(start, column_offsets));
2161
29
    size_t num_items =
2162
29
            column_offsets.get_data().back() - column_offsets.get_data()[start - 1]; // -1 is valid
2163
29
    if (num_items > 0) {
2164
27
        auto column_items_ptr = IColumn::mutate(std::move(column_array.get_data_ptr()));
2165
27
        Defer defer_items {[&] { column_array.get_data_ptr() = std::move(column_items_ptr); }};
2166
27
        if (read_offset_only()) {
2167
            // OFFSET_ONLY mode: skip reading actual item data, fill with defaults
2168
0
            column_items_ptr->insert_many_defaults(num_items);
2169
27
        } else {
2170
27
            size_t num_read = num_items;
2171
27
            bool items_has_null = false;
2172
27
            RETURN_IF_ERROR(
2173
27
                    _item_iterator->next_batch(&num_read, column_items_ptr, &items_has_null));
2174
27
            DCHECK(num_read == num_items);
2175
27
        }
2176
27
    }
2177
2178
29
    if (is_column_nullable(*dst) && read_meta_columns) {
2179
27
        auto null_map_ptr = static_cast<ColumnNullable&>(*dst).get_null_map_column_ptr();
2180
27
        size_t num_read = *n;
2181
        // in not-null to null linked-schemachange mode,
2182
        // actually we do not change dat data include meta in footer,
2183
        // so may dst from changed meta which is nullable but old data is not nullable,
2184
        // if so, we should set null_map to all null by default
2185
27
        if (_null_iterator) {
2186
27
            bool null_signs_has_null = false;
2187
27
            MutableColumnPtr null_map_column = std::move(null_map_ptr);
2188
27
            RETURN_IF_ERROR(
2189
27
                    _null_iterator->next_batch(&num_read, null_map_column, &null_signs_has_null));
2190
27
        } else {
2191
0
            null_map_ptr->insert_many_vals(0, num_read);
2192
0
        }
2193
27
        DCHECK(num_read == *n);
2194
27
    }
2195
2196
29
    return Status::OK();
2197
29
}
2198
2199
0
Status ArrayFileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
2200
0
    RETURN_IF_ERROR(_offset_iterator->init_prefetcher(params));
2201
0
    RETURN_IF_ERROR(_item_iterator->init_prefetcher(params));
2202
0
    if (_array_reader->is_nullable()) {
2203
0
        RETURN_IF_ERROR(_null_iterator->init_prefetcher(params));
2204
0
    }
2205
0
    return Status::OK();
2206
0
}
2207
2208
void ArrayFileColumnIterator::collect_prefetchers(
2209
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
2210
1
        PrefetcherInitMethod init_method) {
2211
1
    if (!need_to_read()) {
2212
0
        return;
2213
0
    }
2214
1
    if (!read_null_map_only()) {
2215
1
        _offset_iterator->collect_prefetchers(prefetchers, init_method);
2216
1
    }
2217
1
    if (_array_reader->is_nullable()) {
2218
1
        _null_iterator->collect_prefetchers(prefetchers, init_method);
2219
1
    }
2220
1
    if (read_offset_only() || read_null_map_only()) {
2221
0
        return;
2222
0
    }
2223
    // the actual data pages to read of item column depends on the read result of offset column,
2224
    // so we can't init prefetch blocks according to rowids, just prefetch all data blocks here.
2225
1
    if (_item_iterator->need_to_read()) {
2226
1
        _item_iterator->collect_prefetchers(prefetchers, PrefetcherInitMethod::ALL_DATA_BLOCKS);
2227
1
    }
2228
1
}
2229
2230
Status ArrayFileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
2231
12
                                               MutableColumnPtr& dst) {
2232
12
    if (!need_to_read()) {
2233
0
        DLOG(INFO) << "Array column iterator column " << _column_name << " skip reading.";
2234
0
        _convert_to_place_holder_column(dst, count);
2235
0
        return Status::OK();
2236
0
    }
2237
2238
12
    _recovery_from_place_holder_column(dst);
2239
2240
26
    for (size_t i = 0; i < count; ++i) {
2241
        // TODO(cambyszju): now read array one by one, need optimize later
2242
14
        RETURN_IF_ERROR(seek_to_ordinal(rowids[i]));
2243
14
        size_t num_read = 1;
2244
14
        RETURN_IF_ERROR(next_batch(&num_read, dst));
2245
14
    }
2246
12
    return Status::OK();
2247
12
}
2248
2249
3
void ArrayFileColumnIterator::set_lazy_output_requirement() {
2250
3
    set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
2251
3
    _item_iterator->set_lazy_output_requirement();
2252
3
}
2253
2254
1
void ArrayFileColumnIterator::remove_pruned_sub_iterators() {
2255
1
    _item_iterator->remove_pruned_sub_iterators();
2256
1
}
2257
2258
92
void ArrayFileColumnIterator::set_read_phase(ReadPhase mode) {
2259
92
    ColumnIterator::set_read_phase(mode);
2260
92
    _item_iterator->set_read_phase(mode);
2261
92
}
2262
2263
0
void ArrayFileColumnIterator::finalize_lazy_phase(MutableColumnPtr& dst) {
2264
0
    _recovery_from_place_holder_column(dst);
2265
0
    auto& column_array = assert_cast<ColumnArray&, TypeCheckOnRelease::DISABLE>(
2266
0
            dst->is_nullable() ? static_cast<ColumnNullable&>(*dst).get_nested_column() : *dst);
2267
0
    auto item_column_ptr = IColumn::mutate(std::move(column_array.get_data_ptr()));
2268
0
    _item_iterator->finalize_lazy_phase(item_column_ptr);
2269
0
    column_array.get_data_ptr() = std::move(item_column_ptr);
2270
0
}
2271
2272
5
void ArrayFileColumnIterator::set_read_requirement(ReadRequirement requirement) {
2273
5
    set_read_requirement_self(requirement);
2274
5
    _item_iterator->set_read_requirement(requirement);
2275
5
}
2276
2277
14
bool ArrayFileColumnIterator::has_lazy_read_target() const {
2278
14
    return _read_requirement == ReadRequirement::LAZY_OUTPUT ||
2279
14
           _item_iterator->has_lazy_read_target();
2280
14
}
2281
2282
Status ArrayFileColumnIterator::set_access_paths(const TColumnAccessPaths& all_access_paths,
2283
22
                                                 const TColumnAccessPaths& predicate_access_paths) {
2284
22
    if (all_access_paths.empty() && predicate_access_paths.empty()) {
2285
0
        return Status::OK();
2286
0
    }
2287
2288
22
    const auto requirement_before_access_path = _read_requirement;
2289
22
    if (!predicate_access_paths.empty()) {
2290
16
        set_read_requirement_self(ReadRequirement::PREDICATE);
2291
16
        DLOG(INFO) << "Array column iterator set sub-column " << _column_name << " to PREDICATE";
2292
16
    }
2293
2294
22
    const bool has_current_level_data_path =
2295
22
            std::ranges::any_of(all_access_paths, [this](const TColumnAccessPath& path) {
2296
22
                return is_current_level_data_access_path(path, _column_name);
2297
22
            });
2298
22
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
2299
22
    auto sub_predicate_access_paths =
2300
22
            DORIS_TRY(_get_sub_access_paths(predicate_access_paths, true));
2301
22
    if (has_current_level_data_path) {
2302
        // A current-level data path already reads the array offsets while materializing the array.
2303
        // Do not let a redundant current-level OFFSET/NULL path switch this iterator into a
2304
        // meta-only mode that would skip item data.
2305
3
        remove_current_level_meta_access_paths(sub_all_access_paths);
2306
3
    }
2307
22
    const bool has_current_level_predicate_meta_path =
2308
22
            std::ranges::any_of(sub_predicate_access_paths, is_current_level_meta_access_path);
2309
    // Current-level predicate metadata paths are consumed by this array iterator and must not be
2310
    // forwarded to the item iterator. The FE keeps all_access_paths as a superset of predicate
2311
    // paths, so meta-only mode is still decided from sub_all_access_paths below.
2312
22
    auto removed =
2313
22
            std::ranges::remove_if(sub_predicate_access_paths, is_current_level_meta_access_path);
2314
22
    sub_predicate_access_paths.erase(removed.begin(), removed.end());
2315
2316
22
    if (sub_predicate_access_paths.empty()) {
2317
        // Check for meta-only modes (OFFSET_ONLY or NULL_MAP_ONLY). Only skip the item
2318
        // iterator when no predicate sub-path needs it in the predicate phase.
2319
10
        _check_and_set_meta_read_mode(requirement_before_access_path, sub_all_access_paths);
2320
10
        if (read_offset_only()) {
2321
0
            _item_iterator->set_read_requirement(ReadRequirement::SKIP);
2322
0
            DLOG(INFO) << "Array column iterator set column " << _column_name
2323
0
                       << " to OFFSET_ONLY meta read mode, item column set to SKIP";
2324
0
            return Status::OK();
2325
0
        }
2326
10
        if (read_null_map_only()) {
2327
2
            _item_iterator->set_read_requirement(ReadRequirement::SKIP);
2328
2
            DLOG(INFO) << "Array column iterator set column " << _column_name
2329
2
                       << " to NULL_MAP_ONLY meta read mode, item column set to SKIP";
2330
2
            return Status::OK();
2331
2
        }
2332
10
    }
2333
    // OFFSET/NULL at the current array level is consumed by this iterator. After deciding that
2334
    // the array is not in a meta-only mode, do not forward those paths to the item iterator.
2335
20
    remove_current_level_meta_access_paths(sub_all_access_paths);
2336
2337
20
    const auto no_sub_column_to_skip = sub_all_access_paths.empty();
2338
20
    const auto no_predicate_sub_column = sub_predicate_access_paths.empty();
2339
2340
20
    if (!no_sub_column_to_skip) {
2341
16
        for (auto& path : sub_all_access_paths) {
2342
16
            if (path.data_access_path.path[0] == ACCESS_ALL) {
2343
15
                path.data_access_path.path[0] = _item_iterator->column_name();
2344
15
            }
2345
16
        }
2346
16
    }
2347
2348
20
    if (no_predicate_sub_column) {
2349
        // Current-level predicate meta paths (OFFSET/NULL) are consumed by the array itself and
2350
        // removed before forwarding paths to the item iterator. If they are the only predicate
2351
        // paths, the item iterator may still be needed later for lazy materialization, but it must
2352
        // not be promoted to PREDICATE. Only propagate the predicate requirement when the
2353
        // parent predicate really applies to the item/whole value instead of array metadata only.
2354
8
        if (_read_requirement == ReadRequirement::PREDICATE &&
2355
8
            !has_current_level_predicate_meta_path) {
2356
2
            _item_iterator->set_read_requirement(ReadRequirement::PREDICATE);
2357
2
        }
2358
12
    } else {
2359
12
        for (auto& path : sub_predicate_access_paths) {
2360
12
            if (path.data_access_path.path[0] == ACCESS_ALL) {
2361
12
                path.data_access_path.path[0] = _item_iterator->column_name();
2362
12
            }
2363
12
        }
2364
12
    }
2365
2366
20
    if (!no_sub_column_to_skip || !no_predicate_sub_column) {
2367
18
        RETURN_IF_ERROR(
2368
18
                _item_iterator->set_access_paths(sub_all_access_paths, sub_predicate_access_paths));
2369
        // Predicate-only item paths stay PREDICATE because this update runs after
2370
        // child set_access_paths() and read requirements are monotonic. Non-predicate item paths are
2371
        // marked as lazy materialization targets.
2372
17
        _item_iterator->set_read_requirement_self(ReadRequirement::LAZY_OUTPUT);
2373
17
    }
2374
19
    return Status::OK();
2375
20
}
2376
2377
////////////////////////////////////////////////////////////////////////////////
2378
// StringFileColumnIterator implementation
2379
////////////////////////////////////////////////////////////////////////////////
2380
2381
StringFileColumnIterator::StringFileColumnIterator(std::shared_ptr<ColumnReader> reader)
2382
2.90k
        : FileColumnIterator(std::move(reader)) {}
2383
2384
2.88k
Status StringFileColumnIterator::init(const ColumnIteratorOptions& opts) {
2385
2.88k
    if (read_offset_only()) {
2386
        // Propagate only_read_offsets to the FileColumnIterator's options
2387
0
        auto modified_opts = opts;
2388
0
        modified_opts.only_read_offsets = true;
2389
0
        return FileColumnIterator::init(modified_opts);
2390
0
    }
2391
2.88k
    return FileColumnIterator::init(opts);
2392
2.88k
}
2393
2394
Status StringFileColumnIterator::set_access_paths(
2395
        const TColumnAccessPaths& all_access_paths,
2396
10
        const TColumnAccessPaths& predicate_access_paths) {
2397
10
    if (all_access_paths.empty() && predicate_access_paths.empty()) {
2398
0
        return Status::OK();
2399
0
    }
2400
2401
10
    const auto requirement_before_access_path = _read_requirement;
2402
10
    if (!predicate_access_paths.empty()) {
2403
8
        set_read_requirement(ReadRequirement::PREDICATE);
2404
8
    }
2405
2406
10
    const bool has_current_level_data_path =
2407
10
            std::ranges::any_of(all_access_paths, [this](const TColumnAccessPath& path) {
2408
10
                return is_current_level_data_access_path(path, _column_name);
2409
10
            });
2410
    // Strip the column name from path[0] before checking for meta-only modes.
2411
    // Raw paths look like ["col_name", "OFFSET"] or ["col_name", "NULL"].
2412
10
    auto sub_all_access_paths = DORIS_TRY(_get_sub_access_paths(all_access_paths));
2413
10
    if (has_current_level_data_path) {
2414
2
        remove_current_level_meta_access_paths(sub_all_access_paths);
2415
2
    }
2416
10
    _check_and_set_meta_read_mode(requirement_before_access_path, sub_all_access_paths);
2417
    // OFFSET_ONLY mode is fundamentally incompatible with CHAR columns:
2418
    // CHAR is stored padded to its declared length (see
2419
    // OlapColumnDataConvertorChar::clone_and_padding), so the per-row length
2420
    // recorded in dict word info / page headers is always the padded length
2421
    // (e.g. 25 for CHAR(25)) — never the logical length expected by length().
2422
    // Recovering the logical length requires scanning the chars buffer with
2423
    // strnlen() (shrink_padding_chars), which OFFSET_ONLY by definition skips.
2424
    // There is no partial-benefit path: any optimization that still produces
2425
    // the correct length() result must read the chars buffer in full.
2426
    //
2427
    // FE (NestedColumnPruning) already filters CHAR slots out of the
2428
    // OFFSET-only access plan, so reaching this branch means an FE/BE
2429
    // contract violation. Fail loudly instead of silently falling back.
2430
10
    if (read_offset_only() && get_reader() != nullptr &&
2431
10
        get_reader()->get_meta_type() == FieldType::OLAP_FIELD_TYPE_CHAR) {
2432
0
        return Status::InternalError(
2433
0
                "OFFSET_ONLY access path is not supported on CHAR column '{}': CHAR is stored "
2434
0
                "padded so the per-row length information available without reading the chars "
2435
0
                "buffer is always the padded length, not the logical length. The FE planner "
2436
0
                "must not emit an OFFSET access path for CHAR columns.",
2437
0
                _column_name);
2438
0
    }
2439
10
    if (read_offset_only()) {
2440
2
        DLOG(INFO) << "String column iterator set column " << _column_name
2441
2
                   << " to OFFSET_ONLY meta read mode";
2442
8
    } else if (read_null_map_only()) {
2443
3
        DLOG(INFO) << "String column iterator set column " << _column_name
2444
3
                   << " to NULL_MAP_ONLY meta read mode";
2445
3
    }
2446
2447
10
    return Status::OK();
2448
10
}
2449
2450
////////////////////////////////////////////////////////////////////////////////
2451
2452
8.88k
FileColumnIterator::FileColumnIterator(std::shared_ptr<ColumnReader> reader) : _reader(reader) {}
2453
2454
void ColumnIterator::_check_and_set_meta_read_mode(ReadRequirement requirement_before_access_path,
2455
52
                                                   const TColumnAccessPaths& sub_all_access_paths) {
2456
52
    _meta_read_mode = MetaReadMode::DEFAULT;
2457
52
    if (requirement_before_access_path != ReadRequirement::NORMAL &&
2458
52
        requirement_before_access_path != ReadRequirement::SKIP) {
2459
        // A stronger requirement means a parent/full-data path already required this iterator
2460
        // to materialize data. In that case a later predicate NULL/OFFSET path is only
2461
        // an additional predicate requirement and must not downgrade the read to
2462
        // meta-only.
2463
6
        return;
2464
6
    }
2465
2466
46
    bool has_offset_path = false;
2467
46
    bool has_null_path = false;
2468
46
    for (const auto& path : sub_all_access_paths) {
2469
37
        if (!is_current_level_meta_access_path(path)) {
2470
21
            _meta_read_mode = MetaReadMode::DEFAULT;
2471
21
            return;
2472
21
        }
2473
16
        const auto& component = path.data_access_path.path[0];
2474
16
        if (StringCaseEqual()(component, ACCESS_OFFSET)) {
2475
5
            has_offset_path = true;
2476
11
        } else {
2477
11
            has_null_path = true;
2478
11
        }
2479
16
    }
2480
25
    if (has_offset_path) {
2481
        // OFFSET_ONLY skips actual child/string data, but nullable complex iterators still
2482
        // materialize the current-level null map. So OFFSET covers OFFSET+NULL metadata.
2483
4
        _meta_read_mode = MetaReadMode::OFFSET_ONLY;
2484
21
    } else if (has_null_path) {
2485
10
        _meta_read_mode = MetaReadMode::NULL_MAP_ONLY;
2486
11
    } else {
2487
11
        _meta_read_mode = MetaReadMode::DEFAULT;
2488
11
    }
2489
25
}
2490
2491
8.54k
Status FileColumnIterator::init(const ColumnIteratorOptions& opts) {
2492
8.54k
    if (_read_requirement == ReadRequirement::SKIP) {
2493
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2494
0
        return Status::OK();
2495
0
    }
2496
2497
8.54k
    _opts = opts;
2498
8.54k
    if (!_opts.use_page_cache) {
2499
8.54k
        _reader->disable_index_meta_cache();
2500
8.54k
    }
2501
8.54k
    RETURN_IF_ERROR(get_block_compression_codec(_reader->get_compression(), &_compress_codec));
2502
8.54k
    if (config::enable_low_cardinality_optimize &&
2503
8.54k
        opts.io_ctx.reader_type == ReaderType::READER_QUERY &&
2504
8.54k
        _reader->encoding_info()->encoding() == DICT_ENCODING) {
2505
139
        auto dict_encoding_type = _reader->get_dict_encoding_type();
2506
        // Only if the column is a predicate column, then we need check the all dict encoding flag
2507
        // because we could rewrite the predciate to accelarate query speed. But if it is not a
2508
        // predicate column, then it is useless. And it has a bad impact on cold read(first time read)
2509
        // because it will load the column's ordinal index and zonemap index and maybe other indices.
2510
        // it has bad impact on primary key query. For example, select * from table where pk = 1, and
2511
        // the table has 2000 columns.
2512
139
        if (dict_encoding_type == ColumnReader::UNKNOWN_DICT_ENCODING && opts.is_predicate_column) {
2513
33
            RETURN_IF_ERROR(seek_to_ordinal(_reader->num_rows() - 1));
2514
33
            _is_all_dict_encoding = _page.is_dict_encoding;
2515
33
            _reader->set_dict_encoding_type(_is_all_dict_encoding
2516
33
                                                    ? ColumnReader::ALL_DICT_ENCODING
2517
33
                                                    : ColumnReader::PARTIAL_DICT_ENCODING);
2518
106
        } else {
2519
106
            _is_all_dict_encoding = dict_encoding_type == ColumnReader::ALL_DICT_ENCODING;
2520
106
        }
2521
139
    }
2522
8.54k
    return Status::OK();
2523
8.54k
}
2524
2525
8.88k
FileColumnIterator::~FileColumnIterator() = default;
2526
2527
0
void FileColumnIterator::_trigger_prefetch_if_eligible(ordinal_t ord) {
2528
0
    std::vector<BlockRange> ranges;
2529
0
    if (_prefetcher->need_prefetch(cast_set<uint32_t>(ord), &ranges)) {
2530
0
        for (const auto& range : ranges) {
2531
0
            _cached_remote_file_reader->prefetch_range(range.offset, range.size, &_opts.io_ctx);
2532
0
        }
2533
0
    }
2534
0
}
2535
2536
24.2k
Status FileColumnIterator::seek_to_ordinal(ordinal_t ord) {
2537
24.2k
    if (!need_to_read()) {
2538
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2539
0
        return Status::OK();
2540
0
    }
2541
2542
24.2k
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
2543
0
            "[verbose] FileColumnIterator::seek_to_ordinal seek to ordinal {}, enable_prefetch={}",
2544
0
            ord, _enable_prefetch);
2545
24.2k
    if (_enable_prefetch) {
2546
0
        _trigger_prefetch_if_eligible(ord);
2547
0
    }
2548
2549
    // if current page contains this row, we don't need to seek
2550
24.2k
    if (!_page || !_page.contains(ord) || !_page_iter.valid()) {
2551
9.01k
        RETURN_IF_ERROR(_reader->seek_at_or_before(ord, &_page_iter, _opts));
2552
9.01k
        RETURN_IF_ERROR(_read_data_page(_page_iter));
2553
9.01k
    }
2554
24.2k
    RETURN_IF_ERROR(_seek_to_pos_in_page(&_page, ord - _page.first_ordinal));
2555
24.2k
    _current_ordinal = ord;
2556
24.2k
    return Status::OK();
2557
24.2k
}
2558
2559
0
Status FileColumnIterator::seek_to_page_start() {
2560
0
    return seek_to_ordinal(_page.first_ordinal);
2561
0
}
2562
2563
26.0k
Status FileColumnIterator::_seek_to_pos_in_page(ParsedPage* page, ordinal_t offset_in_page) const {
2564
26.0k
    if (page->offset_in_page == offset_in_page) {
2565
        // fast path, do nothing
2566
22.9k
        return Status::OK();
2567
22.9k
    }
2568
2569
3.06k
    ordinal_t pos_in_data = offset_in_page;
2570
3.06k
    if (_page.has_null) {
2571
7
        ordinal_t offset_in_data = 0;
2572
7
        ordinal_t skips = offset_in_page;
2573
2574
7
        if (offset_in_page > page->offset_in_page) {
2575
            // forward, reuse null bitmap
2576
3
            skips = offset_in_page - page->offset_in_page;
2577
3
            offset_in_data = page->data_decoder->current_index();
2578
4
        } else {
2579
            // rewind null bitmap, and
2580
4
            page->null_decoder = RleDecoder<bool>((const uint8_t*)page->null_bitmap.data,
2581
4
                                                  cast_set<int>(page->null_bitmap.size), 1);
2582
4
        }
2583
2584
7
        auto skip_nulls = page->null_decoder.Skip(skips);
2585
7
        pos_in_data = offset_in_data + skips - skip_nulls;
2586
7
    }
2587
2588
3.06k
    RETURN_IF_ERROR(page->data_decoder->seek_to_position_in_page(pos_in_data));
2589
3.06k
    page->offset_in_page = offset_in_page;
2590
3.06k
    return Status::OK();
2591
3.06k
}
2592
2593
0
Status FileColumnIterator::next_batch_of_zone_map(size_t* n, MutableColumnPtr& dst) {
2594
0
    return _reader->next_batch_of_zone_map(n, dst);
2595
0
}
2596
2597
20.2k
Status FileColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
2598
20.2k
    if (!need_to_read()) {
2599
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2600
0
        _convert_to_place_holder_column(dst, *n);
2601
0
        return Status::OK();
2602
0
    }
2603
2604
20.2k
    _recovery_from_place_holder_column(dst);
2605
2606
20.2k
    if (read_null_map_only()) {
2607
0
        DLOG(INFO) << "File column iterator column " << _column_name
2608
0
                   << " in NULL_MAP_ONLY mode, reading only null map.";
2609
0
        DORIS_CHECK(is_column_nullable(*dst));
2610
0
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
2611
0
        auto& null_map_data = nullable_col.get_null_map_data();
2612
2613
0
        size_t remaining = *n;
2614
0
        *has_null = false;
2615
0
        while (remaining > 0) {
2616
0
            if (!_page.has_remaining()) {
2617
0
                bool eos = false;
2618
0
                RETURN_IF_ERROR(_load_next_page(&eos));
2619
0
                if (eos) {
2620
0
                    break;
2621
0
                }
2622
0
            }
2623
2624
0
            size_t nrows_in_page = std::min(remaining, _page.remaining());
2625
0
            size_t nrows_to_read = nrows_in_page;
2626
0
            if (_page.has_null) {
2627
0
                while (nrows_to_read > 0) {
2628
0
                    bool is_null = false;
2629
0
                    size_t this_run = _page.null_decoder.GetNextRun(&is_null, nrows_to_read);
2630
0
                    const size_t cur_size = null_map_data.size();
2631
0
                    null_map_data.resize(cur_size + this_run);
2632
0
                    memset(null_map_data.data() + cur_size, is_null ? 1 : 0, this_run);
2633
0
                    if (is_null) {
2634
0
                        *has_null = true;
2635
0
                    }
2636
0
                    nrows_to_read -= this_run;
2637
0
                    _page.offset_in_page += this_run;
2638
0
                    _current_ordinal += this_run;
2639
0
                }
2640
0
            } else {
2641
0
                const size_t cur_size = null_map_data.size();
2642
0
                null_map_data.resize(cur_size + nrows_to_read);
2643
0
                memset(null_map_data.data() + cur_size, 0, nrows_to_read);
2644
0
                _page.offset_in_page += nrows_to_read;
2645
0
                _current_ordinal += nrows_to_read;
2646
0
            }
2647
0
            remaining -= nrows_in_page;
2648
0
        }
2649
0
        *n -= remaining;
2650
0
        nullable_col.get_nested_column().insert_many_defaults(*n);
2651
0
        return Status::OK();
2652
0
    }
2653
2654
20.2k
    size_t curr_size = dst->byte_size();
2655
20.2k
    dst->reserve(*n);
2656
20.2k
    size_t remaining = *n;
2657
20.2k
    *has_null = false;
2658
42.2k
    while (remaining > 0) {
2659
21.9k
        if (!_page.has_remaining()) {
2660
1.76k
            bool eos = false;
2661
1.76k
            RETURN_IF_ERROR(_load_next_page(&eos));
2662
1.76k
            if (eos) {
2663
0
                break;
2664
0
            }
2665
1.76k
        }
2666
2667
        // number of rows to be read from this page
2668
21.9k
        size_t nrows_in_page = std::min(remaining, _page.remaining());
2669
21.9k
        size_t nrows_to_read = nrows_in_page;
2670
21.9k
        if (_page.has_null) {
2671
21.0k
            while (nrows_to_read > 0) {
2672
20.8k
                bool is_null = false;
2673
20.8k
                size_t this_run = _page.null_decoder.GetNextRun(&is_null, nrows_to_read);
2674
                // we use num_rows only for CHECK
2675
20.8k
                size_t num_rows = this_run;
2676
20.8k
                if (!is_null) {
2677
10.5k
                    RETURN_IF_ERROR(_page.data_decoder->next_batch(&num_rows, dst));
2678
10.5k
                    DCHECK_EQ(this_run, num_rows);
2679
10.5k
                } else {
2680
10.3k
                    *has_null = true;
2681
10.3k
                    auto* null_col = check_and_get_column<ColumnNullable>(dst.get());
2682
10.3k
                    if (null_col != nullptr) {
2683
10.3k
                        null_col->insert_many_defaults(this_run);
2684
10.3k
                    } else {
2685
0
                        return Status::InternalError("unexpected column type in column reader");
2686
0
                    }
2687
10.3k
                }
2688
2689
20.8k
                nrows_to_read -= this_run;
2690
20.8k
                _page.offset_in_page += this_run;
2691
20.8k
                _current_ordinal += this_run;
2692
20.8k
            }
2693
21.7k
        } else {
2694
21.7k
            RETURN_IF_ERROR(_page.data_decoder->next_batch(&nrows_to_read, dst));
2695
21.7k
            DCHECK_EQ(nrows_to_read, nrows_in_page);
2696
2697
21.7k
            _page.offset_in_page += nrows_to_read;
2698
21.7k
            _current_ordinal += nrows_to_read;
2699
21.7k
        }
2700
21.9k
        remaining -= nrows_in_page;
2701
21.9k
    }
2702
20.2k
    *n -= remaining;
2703
20.2k
    _opts.stats->bytes_read += (dst->byte_size() - curr_size) + BitmapSize(*n);
2704
2705
20.2k
#ifdef BE_TEST
2706
20.2k
    _reader->check_data_by_zone_map_for_test(dst);
2707
20.2k
#endif
2708
20.2k
    return Status::OK();
2709
20.2k
}
2710
2711
Status FileColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
2712
3.46k
                                          MutableColumnPtr& dst) {
2713
3.46k
    if (!need_to_read()) {
2714
0
        DLOG(INFO) << "File column iterator column " << _column_name << " skip reading.";
2715
0
        _convert_to_place_holder_column(dst, count);
2716
0
        return Status::OK();
2717
0
    }
2718
2719
3.46k
    _recovery_from_place_holder_column(dst);
2720
2721
3.46k
    if (read_null_map_only()) {
2722
1
        DLOG(INFO) << "File column iterator column " << _column_name
2723
1
                   << " in NULL_MAP_ONLY mode, reading only null map by rowids.";
2724
2725
1
        DORIS_CHECK(is_column_nullable(*dst));
2726
1
        auto& nullable_col = assert_cast<ColumnNullable&>(*dst);
2727
1
        auto& null_map_data = nullable_col.get_null_map_data();
2728
1
        const size_t base_size = null_map_data.size();
2729
1
        null_map_data.resize(base_size + count);
2730
2731
1
        size_t remaining = count;
2732
1
        size_t total_read_count = 0;
2733
1
        size_t nrows_to_read = 0;
2734
3
        while (remaining > 0) {
2735
2
            RETURN_IF_ERROR(seek_to_ordinal(rowids[total_read_count]));
2736
2737
2
            nrows_to_read = std::min(remaining, _page.remaining());
2738
2739
2
            if (_page.has_null) {
2740
1
                size_t already_read = 0;
2741
2
                while ((nrows_to_read - already_read) > 0) {
2742
1
                    bool is_null = false;
2743
1
                    size_t this_run = std::min(nrows_to_read - already_read, _page.remaining());
2744
1
                    if (UNLIKELY(this_run == 0)) {
2745
0
                        break;
2746
0
                    }
2747
1
                    this_run = _page.null_decoder.GetNextRun(&is_null, this_run);
2748
2749
1
                    size_t offset = total_read_count + already_read;
2750
1
                    size_t this_read_count = 0;
2751
1
                    rowid_t current_ordinal_in_page =
2752
1
                            cast_set<uint32_t>(_page.offset_in_page + _page.first_ordinal);
2753
2
                    for (size_t i = 0; i < this_run; ++i) {
2754
1
                        if (rowids[offset + i] - current_ordinal_in_page >= this_run) {
2755
0
                            break;
2756
0
                        }
2757
1
                        this_read_count++;
2758
1
                    }
2759
2760
1
                    if (this_read_count > 0) {
2761
1
                        memset(null_map_data.data() + base_size + offset, is_null ? 1 : 0,
2762
1
                               this_read_count);
2763
1
                    }
2764
2765
1
                    already_read += this_read_count;
2766
1
                    _page.offset_in_page += this_run;
2767
1
                }
2768
2769
1
                nrows_to_read = already_read;
2770
1
                total_read_count += nrows_to_read;
2771
1
                remaining -= nrows_to_read;
2772
1
            } else {
2773
1
                rowid_t current_ordinal_in_page =
2774
1
                        cast_set<uint32_t>(_page.offset_in_page + _page.first_ordinal);
2775
1
                size_t rows_in_current_page = 0;
2776
2
                for (size_t i = 0; i < nrows_to_read; ++i) {
2777
2
                    if (rowids[total_read_count + i] - current_ordinal_in_page >= nrows_to_read) {
2778
1
                        break;
2779
1
                    }
2780
1
                    ++rows_in_current_page;
2781
1
                }
2782
1
                DCHECK_GT(rows_in_current_page, 0);
2783
1
                memset(null_map_data.data() + base_size + total_read_count, 0,
2784
1
                       rows_in_current_page);
2785
1
                _page.offset_in_page += rows_in_current_page;
2786
1
                total_read_count += rows_in_current_page;
2787
1
                remaining -= rows_in_current_page;
2788
1
            }
2789
2
        }
2790
2791
1
        null_map_data.resize(base_size + total_read_count);
2792
1
        nullable_col.get_nested_column().insert_many_defaults(total_read_count);
2793
1
        return Status::OK();
2794
1
    }
2795
2796
3.46k
    size_t remaining = count;
2797
3.46k
    size_t total_read_count = 0;
2798
3.46k
    size_t nrows_to_read = 0;
2799
7.44k
    while (remaining > 0) {
2800
3.97k
        RETURN_IF_ERROR(seek_to_ordinal(rowids[total_read_count]));
2801
2802
        // number of rows to be read from this page
2803
3.97k
        nrows_to_read = std::min(remaining, _page.remaining());
2804
2805
3.97k
        if (_page.has_null) {
2806
11
            size_t already_read = 0;
2807
1.10k
            while ((nrows_to_read - already_read) > 0) {
2808
1.09k
                bool is_null = false;
2809
1.09k
                size_t this_run = std::min(nrows_to_read - already_read, _page.remaining());
2810
1.09k
                if (UNLIKELY(this_run == 0)) {
2811
0
                    break;
2812
0
                }
2813
1.09k
                this_run = _page.null_decoder.GetNextRun(&is_null, this_run);
2814
1.09k
                size_t offset = total_read_count + already_read;
2815
1.09k
                size_t this_read_count = 0;
2816
1.09k
                rowid_t current_ordinal_in_page =
2817
1.09k
                        cast_set<uint32_t>(_page.offset_in_page + _page.first_ordinal);
2818
3.38k
                for (size_t i = 0; i < this_run; ++i) {
2819
2.80k
                    if (rowids[offset + i] - current_ordinal_in_page >= this_run) {
2820
510
                        break;
2821
510
                    }
2822
2.29k
                    this_read_count++;
2823
2.29k
                }
2824
2825
1.09k
                auto origin_index = _page.data_decoder->current_index();
2826
1.09k
                if (this_read_count > 0) {
2827
752
                    if (is_null) {
2828
314
                        auto* null_col = check_and_get_column<ColumnNullable>(dst.get());
2829
314
                        if (UNLIKELY(null_col == nullptr)) {
2830
0
                            return Status::InternalError("unexpected column type in column reader");
2831
0
                        }
2832
2833
314
                        null_col->insert_many_defaults(this_read_count);
2834
438
                    } else {
2835
438
                        size_t read_count = this_read_count;
2836
2837
                        // ordinal in nullable columns' data buffer maybe be not continuously(the data doesn't contain null value),
2838
                        // so we need use `page_start_off_in_decoder` to calculate the actual offset in `data_decoder`
2839
438
                        size_t page_start_off_in_decoder =
2840
438
                                _page.first_ordinal + _page.offset_in_page - origin_index;
2841
438
                        RETURN_IF_ERROR(_page.data_decoder->read_by_rowids(
2842
438
                                &rowids[offset], page_start_off_in_decoder, &read_count, dst));
2843
438
                        DCHECK_EQ(read_count, this_read_count);
2844
438
                    }
2845
752
                }
2846
2847
1.09k
                if (!is_null) {
2848
557
                    RETURN_IF_ERROR(
2849
557
                            _page.data_decoder->seek_to_position_in_page(origin_index + this_run));
2850
557
                }
2851
2852
1.09k
                already_read += this_read_count;
2853
1.09k
                _page.offset_in_page += this_run;
2854
1.09k
                DCHECK(_page.offset_in_page <= _page.num_rows);
2855
1.09k
            }
2856
2857
11
            nrows_to_read = already_read;
2858
11
            total_read_count += nrows_to_read;
2859
11
            remaining -= nrows_to_read;
2860
3.96k
        } else {
2861
3.96k
            RETURN_IF_ERROR(_page.data_decoder->read_by_rowids(
2862
3.96k
                    &rowids[total_read_count], _page.first_ordinal, &nrows_to_read, dst));
2863
3.96k
            total_read_count += nrows_to_read;
2864
3.96k
            remaining -= nrows_to_read;
2865
3.96k
        }
2866
3.97k
    }
2867
3.46k
    return Status::OK();
2868
3.46k
}
2869
2870
1.76k
Status FileColumnIterator::_load_next_page(bool* eos) {
2871
1.76k
    _page_iter.next();
2872
1.76k
    if (!_page_iter.valid()) {
2873
0
        *eos = true;
2874
0
        return Status::OK();
2875
0
    }
2876
2877
1.76k
    RETURN_IF_ERROR(_read_data_page(_page_iter));
2878
1.76k
    RETURN_IF_ERROR(_seek_to_pos_in_page(&_page, 0));
2879
1.76k
    *eos = false;
2880
1.76k
    return Status::OK();
2881
1.76k
}
2882
2883
10.7k
Status FileColumnIterator::_read_data_page(const OrdinalPageIndexIterator& iter) {
2884
10.7k
    PageHandle handle;
2885
10.7k
    Slice page_body;
2886
10.7k
    PageFooterPB footer;
2887
10.7k
    _opts.type = DATA_PAGE;
2888
10.7k
    PageDecoderOptions decoder_opts;
2889
10.7k
    decoder_opts.only_read_offsets = _opts.only_read_offsets;
2890
10.7k
    RETURN_IF_ERROR(
2891
10.7k
            _reader->read_page(_opts, iter.page(), &handle, &page_body, &footer, _compress_codec));
2892
    // parse data page
2893
10.7k
    auto st = ParsedPage::create(std::move(handle), page_body, footer.data_page_footer(),
2894
10.7k
                                 _reader->encoding_info(), iter.page(), iter.page_index(), &_page,
2895
10.7k
                                 decoder_opts);
2896
10.7k
    if (!st.ok()) {
2897
0
        LOG(WARNING) << "failed to create ParsedPage, file=" << _opts.file_reader->path().native()
2898
0
                     << ", page_offset=" << iter.page().offset << ", page_size=" << iter.page().size
2899
0
                     << ", page_index=" << iter.page_index() << ", error=" << st;
2900
0
        return st;
2901
0
    }
2902
2903
    // dictionary page is read when the first data page that uses it is read,
2904
    // this is to optimize the memory usage: when there is no query on one column, we could
2905
    // release the memory of dictionary page.
2906
    // note that concurrent iterators for the same column won't repeatedly read dictionary page
2907
    // because of page cache.
2908
10.7k
    if (_reader->encoding_info()->encoding() == DICT_ENCODING) {
2909
4.69k
        auto dict_page_decoder = reinterpret_cast<BinaryDictPageDecoder*>(_page.data_decoder.get());
2910
4.69k
        if (dict_page_decoder->is_dict_encoding()) {
2911
3.06k
            if (_dict_decoder == nullptr) {
2912
3.06k
                RETURN_IF_ERROR(_read_dict_data());
2913
3.06k
                CHECK_NOTNULL(_dict_decoder);
2914
3.06k
            }
2915
2916
3.06k
            dict_page_decoder->set_dict_decoder(cast_set<uint32_t>(_dict_decoder->count()),
2917
3.06k
                                                _dict_word_info.get());
2918
3.06k
        }
2919
4.69k
    }
2920
10.7k
    return Status::OK();
2921
10.7k
}
2922
2923
3.06k
Status FileColumnIterator::_read_dict_data() {
2924
3.06k
    CHECK_EQ(_reader->encoding_info()->encoding(), DICT_ENCODING);
2925
    // read dictionary page
2926
3.06k
    Slice dict_data;
2927
3.06k
    PageFooterPB dict_footer;
2928
3.06k
    _opts.type = INDEX_PAGE;
2929
2930
3.06k
    RETURN_IF_ERROR(_reader->read_page(_opts, _reader->get_dict_page_pointer(), &_dict_page_handle,
2931
3.06k
                                       &dict_data, &dict_footer, _compress_codec));
2932
3.06k
    const EncodingInfo* encoding_info;
2933
    // The dict pool stores strings of the outer column's type. Using the
2934
    // outer type (CHAR vs VARCHAR/STRING) lets the EncodingInfo pick a
2935
    // CHAR-strip pre-decoder so the cached dict page is already unpadded.
2936
3.06k
    RETURN_IF_ERROR(EncodingInfo::get(_reader->get_meta_type(),
2937
3.06k
                                      dict_footer.dict_page_footer().encoding(), &encoding_info));
2938
3.06k
    RETURN_IF_ERROR(encoding_info->create_page_decoder(dict_data, {}, _dict_decoder));
2939
3.06k
    RETURN_IF_ERROR(_dict_decoder->init());
2940
2941
3.06k
    _dict_word_info.reset(new StringRef[_dict_decoder->count()]);
2942
3.06k
    RETURN_IF_ERROR(_dict_decoder->get_dict_word_info(_dict_word_info.get()));
2943
3.06k
    return Status::OK();
2944
3.06k
}
2945
2946
Status FileColumnIterator::get_row_ranges_by_zone_map(
2947
        const AndBlockColumnPredicate* col_predicates,
2948
        const std::vector<std::shared_ptr<const ColumnPredicate>>* delete_predicates,
2949
64
        RowRanges* row_ranges) {
2950
64
    if (_reader->has_zone_map()) {
2951
64
        RETURN_IF_ERROR(_reader->get_row_ranges_by_zone_map(col_predicates, delete_predicates,
2952
64
                                                            row_ranges, _opts));
2953
64
    }
2954
64
    return Status::OK();
2955
64
}
2956
2957
Status FileColumnIterator::get_row_ranges_by_bloom_filter(
2958
64
        const AndBlockColumnPredicate* col_predicates, RowRanges* row_ranges) {
2959
64
    if ((col_predicates->can_do_bloom_filter(false) && _reader->has_bloom_filter_index(false)) ||
2960
64
        (col_predicates->can_do_bloom_filter(true) && _reader->has_bloom_filter_index(true))) {
2961
3
        RETURN_IF_ERROR(_reader->get_row_ranges_by_bloom_filter(col_predicates, row_ranges, _opts));
2962
3
    }
2963
64
    return Status::OK();
2964
64
}
2965
2966
Status FileColumnIterator::get_row_ranges_by_dict(const AndBlockColumnPredicate* col_predicates,
2967
64
                                                  RowRanges* row_ranges) {
2968
64
    if (!_is_all_dict_encoding) {
2969
31
        return Status::OK();
2970
31
    }
2971
2972
33
    if (!_dict_decoder) {
2973
0
        RETURN_IF_ERROR(_read_dict_data());
2974
0
        CHECK_NOTNULL(_dict_decoder);
2975
0
    }
2976
2977
33
    if (!col_predicates->evaluate_and(_dict_word_info.get(), _dict_decoder->count())) {
2978
0
        row_ranges->clear();
2979
0
    }
2980
33
    return Status::OK();
2981
33
}
2982
2983
0
Status FileColumnIterator::init_prefetcher(const SegmentPrefetchParams& params) {
2984
0
    if (_cached_remote_file_reader =
2985
0
                std::dynamic_pointer_cast<io::CachedRemoteFileReader>(_reader->_file_reader);
2986
0
        !_cached_remote_file_reader) {
2987
0
        return Status::OK();
2988
0
    }
2989
0
    _enable_prefetch = true;
2990
0
    _prefetcher = std::make_unique<SegmentPrefetcher>(params.config);
2991
0
    RETURN_IF_ERROR(_prefetcher->init(_reader, params.read_options));
2992
0
    return Status::OK();
2993
0
}
2994
2995
void FileColumnIterator::collect_prefetchers(
2996
        std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>>& prefetchers,
2997
0
        PrefetcherInitMethod init_method) {
2998
0
    if (_prefetcher) {
2999
0
        prefetchers[init_method].emplace_back(_prefetcher.get());
3000
0
    }
3001
0
}
3002
3003
25
Status DefaultValueColumnIterator::init(const ColumnIteratorOptions& opts) {
3004
25
    _opts = opts;
3005
    // be consistent with segment v1
3006
    // if _has_default_value, we should create default column iterator for this column, and
3007
    // "NULL" is a special default value which means the default value is null.
3008
25
    if (_has_default_value) {
3009
1
        if (_default_value == "NULL") {
3010
1
            _default_value_field = Field::create_field<TYPE_NULL>(Null {});
3011
1
        } else {
3012
0
            if (_type == FieldType::OLAP_FIELD_TYPE_ARRAY) {
3013
0
                if (_default_value != "[]") {
3014
0
                    return Status::NotSupported("Array default {} is unsupported", _default_value);
3015
0
                } else {
3016
0
                    _default_value_field = Field::create_field<TYPE_ARRAY>(Array {});
3017
0
                    return Status::OK();
3018
0
                }
3019
0
            } else if (_type == FieldType::OLAP_FIELD_TYPE_STRUCT) {
3020
0
                return Status::NotSupported("STRUCT default type is unsupported");
3021
0
            } else if (_type == FieldType::OLAP_FIELD_TYPE_MAP) {
3022
0
                return Status::NotSupported("MAP default type is unsupported");
3023
0
            }
3024
0
            const auto t = _type;
3025
0
            const auto serde = DataTypeFactory::instance()
3026
0
                                       .create_data_type(t, _precision, _scale, _len)
3027
0
                                       ->get_serde();
3028
0
            RETURN_IF_ERROR(serde->from_fe_string(_default_value, _default_value_field));
3029
0
        }
3030
24
    } else if (_is_nullable) {
3031
24
        _default_value_field = Field::create_field<TYPE_NULL>(Null {});
3032
24
    } else {
3033
0
        return Status::InternalError(
3034
0
                "invalid default value column for no default value and not nullable");
3035
0
    }
3036
25
    return Status::OK();
3037
25
}
3038
3039
8
Status DefaultValueColumnIterator::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
3040
8
    *has_null = _default_value_field.is_null();
3041
8
    _insert_many_default(dst, *n);
3042
8
    return Status::OK();
3043
8
}
3044
3045
Status DefaultValueColumnIterator::read_by_rowids(const rowid_t* rowids, const size_t count,
3046
3
                                                  MutableColumnPtr& dst) {
3047
3
    _insert_many_default(dst, count);
3048
3
    return Status::OK();
3049
3
}
3050
3051
11
void DefaultValueColumnIterator::_insert_many_default(MutableColumnPtr& dst, size_t n) {
3052
11
    if (_default_value_field.is_null()) {
3053
11
        dst->insert_many_defaults(n);
3054
11
    } else {
3055
0
        dst = dst->convert_to_predicate_column_if_dictionary();
3056
0
        dst->insert_duplicate_fields(_default_value_field, n);
3057
0
    }
3058
11
}
3059
3060
0
Status RowIdColumnIteratorV2::next_batch(size_t* n, MutableColumnPtr& dst, bool* has_null) {
3061
0
    auto* string_column = assert_cast<ColumnString*, TypeCheckOnRelease::DISABLE>(dst.get());
3062
3063
0
    for (uint32_t i = 0; i < *n; ++i) {
3064
0
        uint32_t row_id = _current_rowid + i;
3065
0
        GlobalRowLoacationV2 location(_version, _backend_id, _file_id, row_id);
3066
0
        string_column->insert_data(reinterpret_cast<const char*>(&location),
3067
0
                                   sizeof(GlobalRowLoacationV2));
3068
0
    }
3069
0
    _current_rowid += *n;
3070
0
    return Status::OK();
3071
0
}
3072
3073
Status RowIdColumnIteratorV2::read_by_rowids(const rowid_t* rowids, const size_t count,
3074
16
                                             MutableColumnPtr& dst) {
3075
16
    auto* string_column = assert_cast<ColumnString*>(dst.get());
3076
3077
41
    for (size_t i = 0; i < count; ++i) {
3078
25
        uint32_t row_id = rowids[i];
3079
25
        GlobalRowLoacationV2 location(_version, _backend_id, _file_id, row_id);
3080
25
        string_column->insert_data(reinterpret_cast<const char*>(&location),
3081
25
                                   sizeof(GlobalRowLoacationV2));
3082
25
    }
3083
16
    return Status::OK();
3084
16
}
3085
3086
} // namespace doris::segment_v2