Coverage Report

Created: 2026-06-26 04:37

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