Coverage Report

Created: 2026-10-24 10:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format/table/iceberg_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 "format/table/iceberg_reader.h"
19
20
#include <gen_cpp/Descriptors_types.h>
21
#include <gen_cpp/Metrics_types.h>
22
#include <gen_cpp/PlanNodes_types.h>
23
#include <gen_cpp/parquet_types.h>
24
#include <glog/logging.h>
25
#include <parallel_hashmap/phmap.h>
26
#include <rapidjson/document.h>
27
28
#include <algorithm>
29
#include <cstring>
30
#include <functional>
31
#include <memory>
32
#include <optional>
33
34
#include "common/compiler_util.h" // IWYU pragma: keep
35
#include "common/consts.h"
36
#include "common/status.h"
37
#include "core/assert_cast.h"
38
#include "core/block/block.h"
39
#include "core/block/column_with_type_and_name.h"
40
#include "core/column/column.h"
41
#include "core/column/column_nullable.h"
42
#include "core/column/column_string.h"
43
#include "core/column/column_vector.h"
44
#include "core/data_type/data_type_factory.hpp"
45
#include "core/data_type/data_type_nullable.h"
46
#include "core/data_type/data_type_struct.h"
47
#include "core/data_type/define_primitive_type.h"
48
#include "core/data_type/primitive_type.h"
49
#include "core/string_ref.h"
50
#include "core/typeid_cast.h"
51
#include "exprs/aggregate/aggregate_function.h"
52
#include "format/format_common.h"
53
#include "format/generic_reader.h"
54
#include "format/orc/vorc_reader.h"
55
#include "format/parquet/schema_desc.h"
56
#include "format/parquet/vparquet_column_chunk_reader.h"
57
#include "format/table/deletion_vector_reader.h"
58
#include "format/table/iceberg/iceberg_orc_nested_column_utils.h"
59
#include "format/table/iceberg/iceberg_parquet_nested_column_utils.h"
60
#include "format/table/iceberg_scan_semantics.h"
61
#include "format/table/nested_column_access_helper.h"
62
#include "format/table/table_schema_change_helper.h"
63
#include "runtime/runtime_state.h"
64
#include "util/coding.h"
65
#include "util/string_util.h"
66
67
namespace cctz {
68
class time_zone;
69
} // namespace cctz
70
namespace doris {
71
class RowDescriptor;
72
class SlotDescriptor;
73
class TupleDescriptor;
74
75
namespace io {
76
struct IOContext;
77
} // namespace io
78
class VExprContext;
79
} // namespace doris
80
81
namespace doris {
82
namespace {
83
84
constexpr auto kIcebergOrcAttribute = "iceberg.id";
85
86
50
bool orc_subtree_has_iceberg_id(const orc::Type* type, const std::string& attribute) {
87
50
    if (type->hasAttributeKey(attribute)) {
88
13
        return true;
89
13
    }
90
55
    for (uint64_t idx = 0; idx < type->getSubtypeCount(); ++idx) {
91
31
        if (orc_subtree_has_iceberg_id(type->getSubtype(idx), attribute)) {
92
13
            return true;
93
13
        }
94
31
    }
95
24
    return false;
96
37
}
97
98
76
bool parquet_subtree_has_iceberg_id(const FieldSchema& field) {
99
76
    if (field.field_id >= 0) {
100
53
        return true;
101
53
    }
102
23
    return std::ranges::any_of(field.children, parquet_subtree_has_iceberg_id);
103
76
}
104
105
struct ParquetEqualityFieldPath {
106
    std::vector<const FieldSchema*> fields;
107
    std::vector<size_t> child_indexes;
108
};
109
110
bool find_parquet_equality_field_path_by_id(const FieldDescriptor* descriptor, int32_t field_id,
111
23
                                            ParquetEqualityFieldPath* result) {
112
23
    DORIS_CHECK(descriptor != nullptr);
113
23
    DORIS_CHECK(result != nullptr);
114
23
    const auto find = [field_id](const auto& self, const FieldSchema* field,
115
74
                                 ParquetEqualityFieldPath* path) -> bool {
116
74
        DORIS_CHECK(field != nullptr);
117
74
        path->fields.push_back(field);
118
74
        if (field->field_id == field_id) {
119
17
            return true;
120
17
        }
121
63
        for (size_t index = 0; index < field->children.size(); ++index) {
122
22
            path->child_indexes.push_back(index);
123
22
            if (self(self, &field->children[index], path)) {
124
16
                return true;
125
16
            }
126
6
            path->child_indexes.pop_back();
127
6
        }
128
41
        path->fields.pop_back();
129
41
        return false;
130
57
    };
131
58
    for (int index = 0; index < descriptor->size(); ++index) {
132
52
        if (find(find, descriptor->get_column(index), result)) {
133
17
            return true;
134
17
        }
135
52
    }
136
6
    return false;
137
23
}
138
139
bool find_parquet_equality_field_prefix_by_id_path(
140
        const FieldDescriptor* descriptor,
141
        const std::vector<const schema::external::TField*>& table_path,
142
6
        ParquetEqualityFieldPath* result) {
143
6
    DORIS_CHECK(descriptor != nullptr);
144
6
    DORIS_CHECK(result != nullptr);
145
6
    DORIS_CHECK(!table_path.empty());
146
6
    const std::vector<FieldSchema>* candidates = nullptr;
147
7
    for (size_t path_index = 0; path_index < table_path.size(); ++path_index) {
148
7
        const auto* table_field = table_path[path_index];
149
7
        DORIS_CHECK(table_field != nullptr);
150
7
        DORIS_CHECK(table_field->__isset.id);
151
7
        const FieldSchema* match = nullptr;
152
7
        size_t match_index = 0;
153
7
        const size_t candidate_count =
154
7
                candidates == nullptr ? cast_set<size_t>(descriptor->size()) : candidates->size();
155
25
        for (size_t candidate_index = 0; candidate_index < candidate_count; ++candidate_index) {
156
18
            const auto* candidate = candidates == nullptr
157
18
                                            ? descriptor->get_column(cast_set<int>(candidate_index))
158
18
                                            : &(*candidates)[candidate_index];
159
18
            if (candidate != nullptr && candidate->field_id == table_field->id) {
160
0
                match = candidate;
161
0
                match_index = candidate_index;
162
0
                break;
163
0
            }
164
18
        }
165
7
        if (match == nullptr) {
166
7
            const auto wrapper =
167
7
                    candidates == nullptr
168
7
                            ? TableSchemaChangeHelper::BuildTableInfoUtil::
169
6
                                      find_unique_idless_parquet_wrapper_index(
170
6
                                              *table_field, descriptor->get_fields_schema())
171
7
                            : TableSchemaChangeHelper::BuildTableInfoUtil::
172
1
                                      find_unique_idless_parquet_wrapper_index(*table_field,
173
1
                                                                               *candidates);
174
7
            if (wrapper.has_value()) {
175
1
                match_index = *wrapper;
176
1
                match = candidates == nullptr ? descriptor->get_column(cast_set<int>(match_index))
177
1
                                              : &(*candidates)[match_index];
178
1
            }
179
7
        }
180
7
        if (match == nullptr) {
181
6
            return false;
182
6
        }
183
1
        if (!result->fields.empty()) {
184
0
            result->child_indexes.push_back(match_index);
185
0
        }
186
1
        result->fields.push_back(match);
187
1
        candidates = &match->children;
188
1
    }
189
0
    return true;
190
6
}
191
192
std::vector<std::string> equality_field_name_candidates(const schema::external::TField& table_field,
193
21
                                                        const std::string* leaf_fallback) {
194
21
    std::vector<std::string> candidates;
195
21
    if (table_field.__isset.name_mapping) {
196
11
        candidates.insert(candidates.end(), table_field.name_mapping.begin(),
197
11
                          table_field.name_mapping.end());
198
11
        if (table_field.__isset.name_mapping_is_authoritative &&
199
11
            table_field.name_mapping_is_authoritative) {
200
10
            return candidates;
201
10
        }
202
11
    }
203
11
    if (table_field.__isset.name) {
204
11
        candidates.push_back(table_field.name);
205
11
    }
206
11
    if (leaf_fallback != nullptr) {
207
11
        candidates.push_back(*leaf_fallback);
208
11
    }
209
11
    return candidates;
210
21
}
211
212
bool find_parquet_equality_field_prefix_by_name_path(
213
        const FieldDescriptor* descriptor,
214
        const std::vector<const schema::external::TField*>& table_path,
215
7
        const std::string& leaf_fallback, ParquetEqualityFieldPath* result) {
216
7
    DORIS_CHECK(descriptor != nullptr);
217
7
    DORIS_CHECK(result != nullptr);
218
7
    DORIS_CHECK(!table_path.empty());
219
7
    const std::vector<FieldSchema>* children = nullptr;
220
17
    for (size_t path_index = 0; path_index < table_path.size(); ++path_index) {
221
11
        const auto* table_field = table_path[path_index];
222
11
        DORIS_CHECK(table_field != nullptr);
223
11
        const auto names = equality_field_name_candidates(
224
11
                *table_field, path_index + 1 == table_path.size() ? &leaf_fallback : nullptr);
225
11
        const FieldSchema* match = nullptr;
226
11
        size_t match_index = 0;
227
11
        const size_t child_count =
228
11
                children == nullptr ? cast_set<size_t>(descriptor->size()) : children->size();
229
15
        for (const auto& name : names) {
230
29
            for (size_t child_index = 0; child_index < child_count; ++child_index) {
231
24
                const auto* child = children == nullptr
232
24
                                            ? descriptor->get_column(cast_set<int>(child_index))
233
24
                                            : &(*children)[child_index];
234
24
                if (child != nullptr && iequal(child->name, name)) {
235
10
                    match = child;
236
10
                    match_index = child_index;
237
10
                    break;
238
10
                }
239
24
            }
240
15
            if (match != nullptr) {
241
10
                break;
242
10
            }
243
15
        }
244
11
        if (match == nullptr) {
245
1
            return false;
246
1
        }
247
10
        if (!result->fields.empty()) {
248
4
            result->child_indexes.push_back(match_index);
249
4
        }
250
10
        result->fields.push_back(match);
251
10
        children = &match->children;
252
10
    }
253
6
    return true;
254
7
}
255
256
struct OrcEqualityFieldPath {
257
    std::vector<const orc::Type*> fields;
258
    std::vector<std::string> names;
259
    std::vector<size_t> child_indexes;
260
};
261
262
bool find_orc_equality_field_path_by_id(const orc::Type* root, int32_t field_id,
263
12
                                        OrcEqualityFieldPath* result) {
264
12
    DORIS_CHECK(root != nullptr);
265
12
    DORIS_CHECK(result != nullptr);
266
12
    const auto find = [field_id](const auto& self, const orc::Type* field,
267
12
                                 const std::string& field_name,
268
34
                                 OrcEqualityFieldPath* path) -> bool {
269
34
        DORIS_CHECK(field != nullptr);
270
34
        path->fields.push_back(field);
271
34
        path->names.push_back(field_name);
272
34
        if (field->hasAttributeKey(kIcebergOrcAttribute) &&
273
34
            std::stoi(field->getAttributeValue(kIcebergOrcAttribute)) == field_id) {
274
5
            return true;
275
5
        }
276
30
        for (size_t index = 0; index < field->getSubtypeCount(); ++index) {
277
5
            path->child_indexes.push_back(index);
278
5
            if (self(self, field->getSubtype(index), field->getFieldName(index), path)) {
279
4
                return true;
280
4
            }
281
1
            path->child_indexes.pop_back();
282
1
        }
283
25
        path->fields.pop_back();
284
25
        path->names.pop_back();
285
25
        return false;
286
29
    };
287
36
    for (size_t index = 0; index < root->getSubtypeCount(); ++index) {
288
29
        if (find(find, root->getSubtype(index), root->getFieldName(index), result)) {
289
5
            return true;
290
5
        }
291
29
    }
292
7
    return false;
293
12
}
294
295
bool find_orc_equality_field_prefix_by_id_path(
296
        const orc::Type* root, const std::vector<const schema::external::TField*>& table_path,
297
6
        OrcEqualityFieldPath* result) {
298
6
    DORIS_CHECK(root != nullptr);
299
6
    DORIS_CHECK(result != nullptr);
300
6
    DORIS_CHECK(!table_path.empty());
301
6
    const orc::Type* parent = root;
302
7
    for (const auto* table_field : table_path) {
303
7
        DORIS_CHECK(table_field != nullptr);
304
7
        DORIS_CHECK(table_field->__isset.id);
305
7
        const orc::Type* match = nullptr;
306
7
        size_t match_index = 0;
307
25
        for (size_t candidate_index = 0; candidate_index < parent->getSubtypeCount();
308
18
             ++candidate_index) {
309
18
            const auto* candidate = parent->getSubtype(candidate_index);
310
18
            if (candidate->hasAttributeKey(kIcebergOrcAttribute) &&
311
18
                std::stoi(candidate->getAttributeValue(kIcebergOrcAttribute)) == table_field->id) {
312
0
                match = candidate;
313
0
                match_index = candidate_index;
314
0
                break;
315
0
            }
316
18
        }
317
7
        if (match == nullptr) {
318
7
            const auto wrapper = TableSchemaChangeHelper::BuildTableInfoUtil::
319
7
                    find_unique_idless_orc_wrapper_index(*table_field, parent,
320
7
                                                         kIcebergOrcAttribute);
321
7
            if (wrapper.has_value()) {
322
1
                match_index = *wrapper;
323
1
                match = parent->getSubtype(match_index);
324
1
            }
325
7
        }
326
7
        if (match == nullptr) {
327
6
            return false;
328
6
        }
329
1
        if (!result->fields.empty()) {
330
0
            result->child_indexes.push_back(match_index);
331
0
        }
332
1
        result->fields.push_back(match);
333
1
        result->names.push_back(parent->getFieldName(match_index));
334
1
        parent = match;
335
1
    }
336
0
    return true;
337
6
}
338
339
bool find_orc_equality_field_prefix_by_name_path(
340
        const orc::Type* root, const std::vector<const schema::external::TField*>& table_path,
341
6
        const std::string& leaf_fallback, OrcEqualityFieldPath* result) {
342
6
    DORIS_CHECK(root != nullptr);
343
6
    DORIS_CHECK(result != nullptr);
344
6
    DORIS_CHECK(!table_path.empty());
345
6
    const orc::Type* parent = root;
346
15
    for (size_t path_index = 0; path_index < table_path.size(); ++path_index) {
347
10
        const auto* table_field = table_path[path_index];
348
10
        DORIS_CHECK(table_field != nullptr);
349
10
        const auto names = equality_field_name_candidates(
350
10
                *table_field, path_index + 1 == table_path.size() ? &leaf_fallback : nullptr);
351
10
        const orc::Type* match = nullptr;
352
10
        size_t match_index = 0;
353
14
        for (const auto& name : names) {
354
26
            for (size_t child_index = 0; child_index < parent->getSubtypeCount(); ++child_index) {
355
21
                if (iequal(parent->getFieldName(child_index), name)) {
356
9
                    match = parent->getSubtype(child_index);
357
9
                    match_index = child_index;
358
9
                    break;
359
9
                }
360
21
            }
361
14
            if (match != nullptr) {
362
9
                break;
363
9
            }
364
14
        }
365
10
        if (match == nullptr) {
366
1
            return false;
367
1
        }
368
9
        if (!result->fields.empty()) {
369
4
            result->child_indexes.push_back(match_index);
370
4
        }
371
9
        result->fields.push_back(match);
372
9
        result->names.push_back(parent->getFieldName(match_index));
373
9
        parent = match;
374
9
    }
375
5
    return true;
376
6
}
377
378
struct ProjectedIcebergStructChild {
379
    size_t index;
380
    const schema::external::TField* field;
381
};
382
383
std::optional<ProjectedIcebergStructChild> find_projected_iceberg_struct_child(
384
        const schema::external::TField& parent, const schema::external::TField& target,
385
9
        const DataTypeStruct& projected_type) {
386
9
    DORIS_CHECK(parent.__isset.nestedField);
387
9
    DORIS_CHECK(parent.nestedField.__isset.struct_field);
388
9
    DORIS_CHECK(parent.nestedField.struct_field.__isset.fields);
389
9
    DORIS_CHECK(target.__isset.name);
390
9
    DORIS_CHECK(target.__isset.id);
391
392
    // FE keeps current children first and appends historical equality fields to the schema carrier
393
    // by field ID. A dropped and re-added field may therefore appear twice with the same name,
394
    // while the query's DataTypeStruct contains only the current occurrence.
395
9
    size_t schema_name_ordinal = 0;
396
9
    const schema::external::TField* schema_child = nullptr;
397
12
    for (const auto& child_ptr : parent.nestedField.struct_field.fields) {
398
12
        DORIS_CHECK(child_ptr.__isset.field_ptr && child_ptr.field_ptr != nullptr);
399
12
        const auto& child = child_ptr.field_ptr;
400
12
        DORIS_CHECK(child->__isset.name);
401
12
        DORIS_CHECK(child->__isset.id);
402
12
        if (child->name != target.name) {
403
3
            continue;
404
3
        }
405
9
        if (child->id == target.id) {
406
9
            schema_child = child.get();
407
9
            break;
408
9
        }
409
0
        ++schema_name_ordinal;
410
0
    }
411
9
    if (schema_child == nullptr) {
412
0
        return std::nullopt;
413
0
    }
414
415
9
    size_t projected_name_ordinal = 0;
416
12
    for (size_t index = 0; index < projected_type.get_elements().size(); ++index) {
417
11
        if (projected_type.get_element_name(index) != target.name) {
418
3
            continue;
419
3
        }
420
8
        if (projected_name_ordinal == schema_name_ordinal) {
421
8
            return ProjectedIcebergStructChild {.index = index, .field = schema_child};
422
8
        }
423
0
        ++projected_name_ordinal;
424
0
    }
425
1
    return std::nullopt;
426
9
}
427
428
// Resolves a nested equality key inside the projected root column. That column has the table's
429
// projected struct type, not the file's physical struct, so the child indexes come from the
430
// projected type. `found` stays false when the projected type does not hold the key, e.g. when the
431
// key was dropped from the table or the struct was pruned.
432
Status find_projected_equality_key_path(
433
        const schema::external::TField& projected_root,
434
        const std::vector<const schema::external::TField*>& key_path, const DataTypePtr& root_type,
435
9
        std::vector<size_t>* child_indexes, DataTypePtr* leaf_type, bool* found) {
436
9
    DORIS_CHECK(!key_path.empty());
437
9
    DORIS_CHECK(child_indexes != nullptr);
438
9
    DORIS_CHECK(leaf_type != nullptr);
439
9
    DORIS_CHECK(found != nullptr);
440
9
    child_indexes->clear();
441
9
    *found = false;
442
9
    const auto* projected_parent = &projected_root;
443
9
    DataTypePtr current_type = root_type;
444
17
    for (size_t path_index = 1; path_index < key_path.size(); ++path_index) {
445
9
        const auto* child = key_path[path_index];
446
9
        DORIS_CHECK(child != nullptr);
447
9
        if (!projected_parent->__isset.nestedField ||
448
9
            !projected_parent->nestedField.__isset.struct_field ||
449
9
            !projected_parent->nestedField.struct_field.__isset.fields) {
450
0
            return Status::NotSupported(
451
0
                    "Iceberg equality-delete field {} has a non-struct projected-schema parent",
452
0
                    child->name);
453
0
        }
454
9
        const auto* struct_type =
455
9
                typeid_cast<const DataTypeStruct*>(remove_nullable(current_type).get());
456
9
        if (struct_type == nullptr) {
457
0
            return Status::OK();
458
0
        }
459
9
        const auto projected_child =
460
9
                find_projected_iceberg_struct_child(*projected_parent, *child, *struct_type);
461
9
        if (!projected_child.has_value()) {
462
1
            return Status::OK();
463
1
        }
464
8
        child_indexes->push_back(projected_child->index);
465
8
        current_type = struct_type->get_element(projected_child->index);
466
8
        projected_parent = projected_child->field;
467
8
    }
468
8
    *leaf_type = current_type;
469
8
    *found = true;
470
8
    return Status::OK();
471
9
}
472
473
} // namespace
474
475
const std::string IcebergOrcReader::ICEBERG_ORC_ATTRIBUTE = kIcebergOrcAttribute;
476
477
bool IcebergTableReader::_is_fully_dictionary_encoded(
478
8
        const tparquet::ColumnMetaData& column_metadata) {
479
14
    const auto is_dictionary_encoding = [](tparquet::Encoding::type encoding) {
480
14
        return encoding == tparquet::Encoding::PLAIN_DICTIONARY ||
481
14
               encoding == tparquet::Encoding::RLE_DICTIONARY;
482
14
    };
483
12
    const auto is_data_page = [](tparquet::PageType::type page_type) {
484
12
        return page_type == tparquet::PageType::DATA_PAGE ||
485
12
               page_type == tparquet::PageType::DATA_PAGE_V2;
486
12
    };
487
8
    const auto is_level_encoding = [](tparquet::Encoding::type encoding) {
488
2
        return encoding == tparquet::Encoding::RLE || encoding == tparquet::Encoding::BIT_PACKED;
489
2
    };
490
491
    // A column chunk may have a dictionary page but still contain plain-encoded data pages.
492
    // Only treat it as dictionary-coded when all data pages are dictionary encoded.
493
8
    if (column_metadata.__isset.encoding_stats) {
494
7
        bool has_data_page_stats = false;
495
12
        for (const tparquet::PageEncodingStats& enc_stat : column_metadata.encoding_stats) {
496
12
            if (is_data_page(enc_stat.page_type) && enc_stat.count > 0) {
497
8
                has_data_page_stats = true;
498
8
                if (!is_dictionary_encoding(enc_stat.encoding)) {
499
2
                    return false;
500
2
                }
501
8
            }
502
12
        }
503
5
        if (has_data_page_stats) {
504
4
            return true;
505
4
        }
506
5
    }
507
508
2
    bool has_dict_encoding = false;
509
2
    bool has_nondict_encoding = false;
510
3
    for (const tparquet::Encoding::type& encoding : column_metadata.encodings) {
511
3
        if (is_dictionary_encoding(encoding)) {
512
1
            has_dict_encoding = true;
513
1
        }
514
515
3
        if (!is_dictionary_encoding(encoding) && !is_level_encoding(encoding)) {
516
2
            has_nondict_encoding = true;
517
2
            break;
518
2
        }
519
3
    }
520
2
    if (!has_dict_encoding || has_nondict_encoding) {
521
2
        return false;
522
2
    }
523
524
0
    return true;
525
2
}
526
527
// ============================================================================
528
// IcebergParquetReader: on_before_init_reader (Parquet-specific schema matching)
529
// ============================================================================
530
// This format-specific setup mirrors the existing reader initialization sequence.
531
// NOLINTNEXTLINE(readability-function-cognitive-complexity,readability-function-size)
532
30
Status IcebergParquetReader::on_before_init_reader(ReaderInitContext* ctx) {
533
30
    _column_descs = ctx->column_descs;
534
30
    _fill_col_name_to_block_idx = ctx->col_name_to_block_idx;
535
30
    _file_format = Fileformat::PARQUET;
536
30
    set_preserve_binary_uuid(true);
537
538
    // Get file metadata schema first (available because _open_file() already ran)
539
30
    const FieldDescriptor* field_desc = nullptr;
540
30
    RETURN_IF_ERROR(this->get_file_metadata_schema(&field_desc));
541
30
    DCHECK(field_desc != nullptr);
542
543
    // Build table_info_node by field_id or name matching.
544
    // This must happen BEFORE column classification so we can use children_column_exists
545
    // to check if a column exists in the file (by field ID, not name).
546
30
    if (!get_scan_params().__isset.history_schema_info ||
547
30
        get_scan_params().history_schema_info.empty()) [[unlikely]] {
548
1
        RETURN_IF_ERROR(BuildTableInfoUtil::by_parquet_name(ctx->tuple_descriptor, *field_desc,
549
1
                                                            ctx->table_info_node));
550
29
    } else {
551
29
        RETURN_IF_ERROR(BuildTableInfoUtil::by_parquet_field_id_with_name_mapping(
552
29
                get_scan_params().history_schema_info.front().root_field, *field_desc,
553
29
                ctx->table_info_node, supports_iceberg_scan_semantics_v1(&get_scan_params())));
554
29
    }
555
556
30
    std::unordered_set<std::string> partition_col_names;
557
30
    if (ctx->range->__isset.columns_from_path_keys) {
558
0
        partition_col_names.insert(ctx->range->columns_from_path_keys.begin(),
559
0
                                   ctx->range->columns_from_path_keys.end());
560
0
    }
561
562
    // Single pass: classify columns, detect $row_id, handle partition fallback.
563
30
    bool has_partition_from_path = false;
564
43
    for (const auto& desc : *ctx->column_descs) {
565
43
        if (desc.category == ColumnCategory::SYNTHESIZED) {
566
0
            if (desc.name == BeConsts::ICEBERG_ROWID_COL) {
567
0
                this->register_synthesized_column_handler(
568
0
                        BeConsts::ICEBERG_ROWID_COL, [this](Block* block, size_t rows) -> Status {
569
0
                            return _fill_iceberg_row_id(block, rows);
570
0
                        });
571
0
                continue;
572
0
            } else if (desc.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
573
0
                auto topn_row_id_column_iter = _create_topn_row_id_column_iterator();
574
0
                this->register_synthesized_column_handler(
575
0
                        desc.name,
576
0
                        [iter = std::move(topn_row_id_column_iter), this, &desc](
577
0
                                Block* block, size_t rows) -> Status {
578
0
                            return fill_topn_row_id(iter, desc.name, block, rows);
579
0
                        });
580
0
                continue;
581
0
            }
582
43
        } else if (desc.category == ColumnCategory::PARTITION_KEY) {
583
0
            bool has_partition_value = partition_col_names.contains(desc.name);
584
0
            bool exists_in_file = ctx->table_info_node->children_column_exists(desc.name);
585
0
            if (!has_partition_value || exists_in_file) {
586
                // Keep PARTITION_KEY category stable for scan planning, but still read
587
                // from file when the column exists there.
588
0
                ctx->column_names.push_back(desc.name);
589
0
                continue;
590
0
            }
591
0
            has_partition_from_path = true;
592
43
        } else if (desc.category == ColumnCategory::REGULAR) {
593
43
            ctx->column_names.push_back(desc.name);
594
43
        } else if (desc.category == ColumnCategory::GENERATED) {
595
0
            _init_row_lineage_columns();
596
0
            if (desc.name == ROW_LINEAGE_ROW_ID) {
597
0
                ctx->column_names.push_back(desc.name);
598
0
                this->register_generated_column_handler(
599
0
                        ROW_LINEAGE_ROW_ID, [this](Block* block, size_t rows) -> Status {
600
0
                            return _fill_row_lineage_row_id(block, rows);
601
0
                        });
602
0
                continue;
603
0
            } else if (desc.name == ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER) {
604
0
                ctx->column_names.push_back(desc.name);
605
0
                this->register_generated_column_handler(
606
0
                        ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER,
607
0
                        [this](Block* block, size_t rows) -> Status {
608
0
                            return _fill_row_lineage_last_updated_sequence_number(block, rows);
609
0
                        });
610
0
                continue;
611
0
            }
612
0
        }
613
43
    }
614
615
    // Set up partition value extraction if any partition columns need filling from path
616
30
    if (has_partition_from_path) {
617
0
        RETURN_IF_ERROR(_extract_partition_values(*ctx->range, ctx->tuple_descriptor,
618
0
                                                  _fill_partition_values,
619
0
                                                  &_fill_partition_value_is_null));
620
0
    }
621
622
30
    _all_required_col_names = ctx->column_names;
623
624
    // Create column IDs from field descriptor
625
30
    auto column_id_result =
626
30
            _create_column_ids(field_desc, ctx->tuple_descriptor, ctx->table_info_node);
627
30
    ctx->column_ids = std::move(column_id_result.column_ids);
628
30
    ctx->filter_column_ids = std::move(column_id_result.filter_column_ids);
629
630
    // Build field_id -> block_column_name mapping for equality delete filtering.
631
    // This was previously done in init_reader() column matching (pre-CRTP refactoring).
632
43
    for (const auto* slot : ctx->tuple_descriptor->slots()) {
633
43
        _id_to_block_column_name.emplace(slot->col_unique_id(), slot->col_name());
634
43
    }
635
636
    // Process delete files (must happen before _do_init_reader so expand col IDs are included)
637
30
    RETURN_IF_ERROR(_init_row_filters());
638
639
    // Add expand column IDs for equality delete and remap expand column names
640
    // to match master's behavior:
641
    // - Use field_id to find the actual file column name in Parquet schema
642
    // - Prefix with __equality_delete_column__ to avoid name conflicts
643
    // - Correctly map table_col_name → file_col_name in table_info_node
644
30
    const static std::string EQ_DELETE_PRE = "__equality_delete_column__";
645
30
    bool all_file_columns_have_field_ids = true;
646
30
    bool any_file_column_has_field_id = false;
647
99
    for (int i = 0; i < field_desc->size(); ++i) {
648
69
        const auto* field_schema = field_desc->get_column(i);
649
69
        if (field_schema) {
650
69
            if (field_schema->field_id < 0) {
651
19
                all_file_columns_have_field_ids = false;
652
19
            }
653
69
            if (parquet_subtree_has_iceberg_id(*field_schema)) {
654
53
                any_file_column_has_field_id = true;
655
53
            }
656
69
        }
657
69
    }
658
30
    const bool use_field_ids_for_hidden_keys =
659
30
            supports_iceberg_scan_semantics_v1(&get_scan_params())
660
30
                    ? any_file_column_has_field_id
661
30
                    : all_file_columns_have_field_ids;
662
30
    const auto find_file_column_by_name = [&](const std::string& name) -> const FieldSchema* {
663
0
        for (int j = 0; j < field_desc->size(); ++j) {
664
0
            const auto* candidate = field_desc->get_column(j);
665
0
            if (candidate != nullptr && iequal(candidate->name, name)) {
666
0
                return candidate;
667
0
            }
668
0
        }
669
0
        return nullptr;
670
0
    };
671
30
    std::unordered_map<int32_t, const SlotDescriptor*> projected_slots;
672
43
    for (const auto* slot : ctx->tuple_descriptor->slots()) {
673
43
        projected_slots.emplace(slot->col_unique_id(), slot);
674
43
    }
675
    // Finds a nested key inside its root struct when the query projects that root, so the key is
676
    // taken from the projected column instead of reading the root a second time.
677
30
    const auto find_projected_root = [&](int32_t field_id, const DataTypePtr& key_type,
678
30
                                         std::string* root_name,
679
30
                                         std::vector<size_t>* child_indexes) -> Status {
680
20
        const auto key_path = _find_schema_field_path(field_id);
681
20
        if (key_path.empty()) {
682
0
            return Status::OK();
683
0
        }
684
20
        DORIS_CHECK(key_path.front()->__isset.id);
685
20
        const auto slot = projected_slots.find(key_path.front()->id);
686
20
        if (slot == projected_slots.end()) {
687
11
            return Status::OK();
688
11
        }
689
9
        std::vector<const schema::external::TField*> root_path;
690
9
        if (!_find_schema_field_path_in_root(_current_schema_root(), key_path.front()->id,
691
9
                                             &root_path)) {
692
0
            return Status::OK();
693
0
        }
694
9
        DORIS_CHECK(root_path.size() == 1);
695
9
        DataTypePtr leaf_type;
696
9
        bool found = false;
697
9
        RETURN_IF_ERROR(find_projected_equality_key_path(*root_path.front(), key_path,
698
9
                                                         slot->second->type(), child_indexes,
699
9
                                                         &leaf_type, &found));
700
        // The projected leaf has the table's current type. A key written before a type promotion
701
        // (INT promoted to BIGINT) keeps its own type, so it still reads the physical root.
702
9
        if (found && remove_nullable(leaf_type)->equals(*remove_nullable(key_type))) {
703
8
            *root_name = slot->second->col_name();
704
8
        }
705
9
        return Status::OK();
706
9
    };
707
    // Physical root struct -> the carrier that reads it for every hidden key under that root.
708
30
    std::unordered_map<std::string, std::string> physical_root_carriers;
709
710
    // Rebuild _expand_col_names with proper file-column-based names
711
30
    std::vector<std::string> new_expand_col_names;
712
30
    DORIS_CHECK(_expand_col_names.size() == _expand_col_field_ids.size());
713
30
    DORIS_CHECK(_expand_col_names.size() == _expand_columns.size());
714
60
    for (size_t i = 0; i < _expand_col_names.size(); ++i) {
715
30
        const auto& old_name = _expand_col_names[i];
716
30
        const int32_t field_id = _expand_col_field_ids[i];
717
718
30
        const FieldSchema* file_column = nullptr;
719
30
        ParquetEqualityFieldPath file_path;
720
30
        bool complete_file_path = false;
721
30
        if (use_field_ids_for_hidden_keys) {
722
23
            complete_file_path =
723
23
                    find_parquet_equality_field_path_by_id(field_desc, field_id, &file_path);
724
23
            if (!complete_file_path && supports_iceberg_scan_semantics_v2(&get_scan_params())) {
725
6
                const auto table_path = _find_schema_field_path(field_id);
726
6
                if (!table_path.empty()) {
727
6
                    complete_file_path = find_parquet_equality_field_prefix_by_id_path(
728
6
                            field_desc, table_path, &file_path);
729
6
                }
730
6
            }
731
23
            if (!file_path.fields.empty()) {
732
18
                file_column = file_path.fields.front();
733
18
            }
734
23
        } else {
735
7
            const auto table_path = _find_schema_field_path(field_id);
736
7
            if (!table_path.empty()) {
737
7
                complete_file_path = find_parquet_equality_field_prefix_by_name_path(
738
7
                        field_desc, table_path, old_name, &file_path);
739
7
                if (!file_path.fields.empty()) {
740
6
                    file_column = file_path.fields.front();
741
6
                }
742
7
            } else {
743
0
                file_column = find_file_column_by_name(old_name);
744
0
                complete_file_path = file_column != nullptr;
745
0
            }
746
7
        }
747
748
30
        std::string leaf_name = old_name;
749
30
        if (!file_path.fields.empty()) {
750
24
            leaf_name = file_path.fields.back()->name;
751
24
        } else if (file_column != nullptr) {
752
0
            leaf_name = file_column->name;
753
0
        }
754
30
        const std::string file_col_name = file_column == nullptr ? old_name : file_column->name;
755
30
        std::string table_col_name = EQ_DELETE_PRE + std::to_string(field_id) + "_" + leaf_name;
756
757
        // Update _id_to_block_column_name
758
30
        if (field_id >= 0) {
759
30
            _id_to_block_column_name[field_id] = table_col_name;
760
30
        }
761
762
        // Update _expand_columns name
763
30
        _expand_columns[i].name = table_col_name;
764
765
30
        if (file_column == nullptr) {
766
6
            RETURN_IF_ERROR(_register_missing_equality_delete_column(field_id, table_col_name,
767
6
                                                                     _expand_columns[i].type));
768
            // The old data file predates this equality key. Its logical initial default is appended
769
            // after the read; do not advertise it to Parquet as a physical child.
770
6
            new_expand_col_names.push_back(table_col_name);
771
6
            continue;
772
6
        }
773
774
24
        new_expand_col_names.push_back(table_col_name);
775
776
        // A hidden nested key is read through its containing top-level struct. V1 column IDs are
777
        // pre-order ranges, so include the complete subtree before extracting the primitive leaf.
778
        // A projected root that serves as the key's source then reads the key's leaf as well.
779
24
        for (uint64_t column_id = file_column->get_column_id();
780
78
             column_id <= file_column->get_max_column_id(); ++column_id) {
781
54
            ctx->column_ids.insert(column_id);
782
54
        }
783
784
24
        if (!complete_file_path || !file_path.child_indexes.empty()) {
785
            // Parquet reads each table column through its own column reader. Without the two
786
            // branches below, a projected root and a carrier, or two carriers of keys under one
787
            // root, all named the same file column, and only one of them was read. Example:
788
            // `SELECT id, payload` with an equality delete on payload.existing returned an empty
789
            // payload, or no rows at all when payload was listed first.
790
21
            std::string projected_root_name;
791
21
            std::vector<size_t> projected_child_indexes;
792
21
            if (complete_file_path) {
793
20
                RETURN_IF_ERROR(find_projected_root(field_id, _expand_columns[i].type,
794
20
                                                    &projected_root_name,
795
20
                                                    &projected_child_indexes));
796
20
            }
797
21
            if (!projected_root_name.empty()) {
798
                // The query projects payload and the file has payload.existing: extract the key
799
                // from the projected payload column.
800
8
                _nested_equality_delete_columns.push_back({
801
8
                        .field_id = field_id,
802
8
                        .block_name = table_col_name,
803
8
                        .leaf_type = _expand_columns[i].type,
804
8
                        .child_indexes = std::move(projected_child_indexes),
805
8
                        .missing_value = nullptr,
806
8
                        .source_block_name = std::move(projected_root_name),
807
8
                });
808
8
                continue;
809
8
            }
810
13
            ColumnPtr missing_value;
811
13
            if (!complete_file_path) {
812
1
                RETURN_IF_ERROR(_create_missing_equality_delete_value(
813
1
                        field_id, _expand_columns[i].type, file_path.fields.size(),
814
1
                        &missing_value));
815
1
            }
816
13
            const auto root_carrier = physical_root_carriers.find(file_column->name);
817
13
            if (root_carrier != physical_root_carriers.end()) {
818
                // Keys payload.a and payload.b: the carrier of payload.a reads payload, and
819
                // payload.b is extracted from that carrier's column.
820
2
                _nested_equality_delete_columns.push_back({
821
2
                        .field_id = field_id,
822
2
                        .block_name = table_col_name,
823
2
                        .leaf_type = _expand_columns[i].type,
824
2
                        .child_indexes = file_path.child_indexes,
825
2
                        .missing_value = std::move(missing_value),
826
2
                        .source_block_name = root_carrier->second,
827
2
                });
828
2
                continue;
829
2
            }
830
11
            physical_root_carriers.emplace(file_column->name, table_col_name);
831
11
            _nested_equality_delete_columns.push_back({
832
11
                    .field_id = field_id,
833
11
                    .block_name = table_col_name,
834
11
                    .leaf_type = _expand_columns[i].type,
835
11
                    .child_indexes = file_path.child_indexes,
836
11
                    .missing_value = std::move(missing_value),
837
11
            });
838
11
            _expand_columns[i].type = make_nullable(file_column->data_type);
839
11
            _expand_columns[i].column = _expand_columns[i].type->create_column();
840
11
        }
841
842
        // Register in table_info_node: table_col_name → file_col_name
843
14
        ctx->column_names.push_back(table_col_name);
844
14
        ctx->table_info_node->add_children(table_col_name, file_col_name,
845
14
                                           TableSchemaChangeHelper::ConstNode::get_instance());
846
14
    }
847
30
    _expand_col_names = std::move(new_expand_col_names);
848
849
    // Enable group filtering for Iceberg
850
30
    _filter_groups = true;
851
852
30
    return Status::OK();
853
30
}
854
855
// ============================================================================
856
// IcebergParquetReader: _create_column_ids
857
// ============================================================================
858
ColumnIdResult IcebergParquetReader::_create_column_ids(
859
        const FieldDescriptor* field_desc, const TupleDescriptor* tuple_descriptor,
860
37
        const std::shared_ptr<TableSchemaChangeHelper::Node>& table_info_node) {
861
37
    auto* mutable_field_desc = const_cast<FieldDescriptor*>(field_desc);
862
37
    mutable_field_desc->assign_ids();
863
864
37
    std::unordered_map<int, const FieldSchema*> iceberg_id_to_field_schema_map;
865
156
    for (int i = 0; i < field_desc->size(); ++i) {
866
119
        const auto* field_schema = field_desc->get_column(i);
867
119
        if (!field_schema) {
868
0
            continue;
869
0
        }
870
119
        int iceberg_id = field_schema->field_id;
871
119
        iceberg_id_to_field_schema_map[iceberg_id] = field_schema;
872
119
    }
873
874
37
    std::set<uint64_t> column_ids;
875
37
    std::set<uint64_t> filter_column_ids;
876
877
37
    auto process_access_paths = [](const FieldSchema* parquet_field,
878
37
                                   const std::vector<TColumnAccessPath>& access_paths,
879
37
                                   std::set<uint64_t>& out_ids) {
880
24
        process_nested_access_paths(
881
24
                parquet_field, access_paths, out_ids,
882
24
                [](const FieldSchema* field) { return field->get_column_id(); },
883
24
                [](const FieldSchema* field) { return field->get_max_column_id(); },
884
24
                IcebergParquetNestedColumnUtils::extract_nested_column_ids);
885
24
    };
886
887
    // The Iceberg schema-mapping root is a StructNode whose registered children are the real
888
    // table columns. When present, resolve each column by name through it so the column-id set
889
    // stays consistent with the schema-mapping decision (BY_ID or BY_NAME/name-mapping);
890
    // otherwise fall back to matching by Iceberg field id.
891
37
    const auto* struct_node =
892
37
            dynamic_cast<const TableSchemaChangeHelper::StructNode*>(table_info_node.get());
893
894
58
    for (const auto* slot : tuple_descriptor->slots()) {
895
58
        const FieldSchema* field_schema = nullptr;
896
58
        if (struct_node != nullptr) {
897
            // Synthesized/metadata slots (e.g. the TopN global row-id or the $row_id column) are
898
            // never registered as children, so check membership before querying: calling
899
            // children_column_exists() on an unregistered name DCHECK-aborts in debug builds and
900
            // throws std::out_of_range from .at() in release builds.
901
45
            if (struct_node->get_children().contains(slot->col_name()) &&
902
45
                struct_node->children_column_exists(slot->col_name())) {
903
                // Use the physical child selected by the schema-mapping pass. This keeps partial-id
904
                // files in BY_NAME mode from binding a projected column through an unrelated stale
905
                // field id.
906
42
                const auto& file_column_name =
907
42
                        struct_node->children_file_column_name(slot->col_name());
908
59
                for (int i = 0; i < field_desc->size(); ++i) {
909
59
                    const auto* candidate = field_desc->get_column(i);
910
59
                    if (candidate != nullptr && candidate->name == file_column_name) {
911
42
                        field_schema = candidate;
912
42
                        break;
913
42
                    }
914
59
                }
915
42
                DORIS_CHECK(field_schema != nullptr);
916
42
            }
917
45
        } else {
918
13
            auto it = iceberg_id_to_field_schema_map.find(slot->col_unique_id());
919
13
            if (it != iceberg_id_to_field_schema_map.end()) {
920
13
                field_schema = it->second;
921
13
            }
922
13
        }
923
58
        if (field_schema == nullptr) {
924
3
            continue;
925
3
        }
926
927
55
        if ((slot->col_type() != TYPE_STRUCT && slot->col_type() != TYPE_ARRAY &&
928
55
             slot->col_type() != TYPE_MAP)) {
929
37
            column_ids.insert(field_schema->column_id);
930
37
            if (slot->is_predicate()) {
931
0
                filter_column_ids.insert(field_schema->column_id);
932
0
            }
933
37
            continue;
934
37
        }
935
936
18
        const auto& all_access_paths = slot->all_access_paths();
937
18
        process_access_paths(field_schema, all_access_paths, column_ids);
938
939
18
        const auto& predicate_access_paths = slot->predicate_access_paths();
940
18
        if (!predicate_access_paths.empty()) {
941
6
            process_access_paths(field_schema, predicate_access_paths, filter_column_ids);
942
6
        }
943
18
    }
944
37
    return {std::move(column_ids), std::move(filter_column_ids)};
945
37
}
946
947
// ============================================================================
948
// IcebergParquetReader: _read_position_delete_file
949
// ============================================================================
950
Status IcebergParquetReader::_read_position_delete_file(const TFileRangeDesc* delete_range,
951
2
                                                        DeleteFile* position_delete) {
952
2
    ParquetReader parquet_delete_reader(get_profile(), get_scan_params(), *delete_range,
953
2
                                        READ_DELETE_FILE_BATCH_SIZE, &get_state()->timezone_obj(),
954
2
                                        get_io_ctx(), get_state(), _meta_cache);
955
    // The delete file range has size=-1 (read whole file). We must disable
956
    // row group filtering before init; otherwise _do_init_reader returns EndOfFile
957
    // when _filter_groups && _range_size < 0.
958
2
    ParquetInitContext delete_ctx;
959
2
    delete_ctx.filter_groups = false;
960
2
    delete_ctx.column_names = delete_file_col_names;
961
2
    delete_ctx.col_name_to_block_idx =
962
2
            const_cast<std::unordered_map<std::string, uint32_t>*>(&DELETE_COL_NAME_TO_BLOCK_IDX);
963
2
    RETURN_IF_ERROR(parquet_delete_reader.init_reader(&delete_ctx));
964
965
0
    const tparquet::FileMetaData* meta_data = parquet_delete_reader.get_meta_data();
966
0
    bool dictionary_coded = true;
967
0
    for (const auto& row_group : meta_data->row_groups) {
968
0
        const auto& column_chunk = row_group.columns[ICEBERG_FILE_PATH_INDEX];
969
0
        if (!(column_chunk.__isset.meta_data && has_dict_page(column_chunk.meta_data))) {
970
0
            dictionary_coded = false;
971
0
            break;
972
0
        }
973
0
    }
974
0
    DataTypePtr data_type_file_path = make_nullable(std::make_shared<DataTypeString>());
975
0
    DataTypePtr data_type_pos = make_nullable(std::make_shared<DataTypeInt64>());
976
0
    bool eof = false;
977
0
    while (!eof) {
978
0
        Block block = {
979
0
                dictionary_coded
980
0
                        ? ColumnWithTypeAndName {ColumnNullable::create(ColumnDictI32::create(),
981
0
                                                                        ColumnUInt8::create()),
982
0
                                                 data_type_file_path, ICEBERG_FILE_PATH}
983
0
                        : ColumnWithTypeAndName {data_type_file_path, ICEBERG_FILE_PATH},
984
985
0
                {data_type_pos, ICEBERG_ROW_POS}};
986
0
        size_t read_rows = 0;
987
0
        RETURN_IF_ERROR(parquet_delete_reader.get_next_block(&block, &read_rows, &eof));
988
989
0
        if (read_rows <= 0) {
990
0
            break;
991
0
        }
992
0
        RETURN_IF_ERROR(_gen_position_delete_file_range(block, position_delete, read_rows,
993
0
                                                        dictionary_coded));
994
0
    }
995
0
    return Status::OK();
996
0
};
997
998
// ============================================================================
999
// IcebergOrcReader: on_before_init_reader (ORC-specific schema matching)
1000
// ============================================================================
1001
// This format-specific setup mirrors the existing reader initialization sequence.
1002
// NOLINTNEXTLINE(readability-function-cognitive-complexity,readability-function-size)
1003
20
Status IcebergOrcReader::on_before_init_reader(ReaderInitContext* ctx) {
1004
20
    _column_descs = ctx->column_descs;
1005
20
    _fill_col_name_to_block_idx = ctx->col_name_to_block_idx;
1006
20
    _file_format = Fileformat::ORC;
1007
1008
    // Get ORC file type first (available because _create_file_reader() already ran)
1009
20
    const orc::Type* orc_type_ptr = nullptr;
1010
20
    RETURN_IF_ERROR(this->get_file_type(&orc_type_ptr));
1011
1012
    // Build table_info_node by field_id or name matching.
1013
    // This must happen BEFORE column classification so we can use children_column_exists
1014
    // to check if a column exists in the file (by field ID, not name).
1015
20
    if (!get_scan_params().__isset.history_schema_info ||
1016
20
        get_scan_params().history_schema_info.empty()) [[unlikely]] {
1017
1
        RETURN_IF_ERROR(BuildTableInfoUtil::by_orc_name(ctx->tuple_descriptor, orc_type_ptr,
1018
1
                                                        ctx->table_info_node));
1019
19
    } else {
1020
19
        RETURN_IF_ERROR(BuildTableInfoUtil::by_orc_field_id_with_name_mapping(
1021
19
                get_scan_params().history_schema_info.front().root_field, orc_type_ptr,
1022
19
                ICEBERG_ORC_ATTRIBUTE, ctx->table_info_node,
1023
19
                supports_iceberg_scan_semantics_v1(&get_scan_params())));
1024
19
    }
1025
1026
20
    std::unordered_set<std::string> partition_col_names;
1027
20
    if (ctx->range->__isset.columns_from_path_keys) {
1028
0
        partition_col_names.insert(ctx->range->columns_from_path_keys.begin(),
1029
0
                                   ctx->range->columns_from_path_keys.end());
1030
0
    }
1031
1032
    // Single pass: classify columns, detect $row_id, handle partition fallback.
1033
20
    bool has_partition_from_path = false;
1034
27
    for (const auto& desc : *ctx->column_descs) {
1035
27
        if (desc.category == ColumnCategory::SYNTHESIZED) {
1036
0
            if (desc.name == BeConsts::ICEBERG_ROWID_COL) {
1037
0
                this->register_synthesized_column_handler(
1038
0
                        BeConsts::ICEBERG_ROWID_COL, [this](Block* block, size_t rows) -> Status {
1039
0
                            return _fill_iceberg_row_id(block, rows);
1040
0
                        });
1041
0
                continue;
1042
0
            } else if (desc.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
1043
0
                auto topn_row_id_column_iter = _create_topn_row_id_column_iterator();
1044
0
                this->register_synthesized_column_handler(
1045
0
                        desc.name,
1046
0
                        [iter = std::move(topn_row_id_column_iter), this, &desc](
1047
0
                                Block* block, size_t rows) -> Status {
1048
0
                            return fill_topn_row_id(iter, desc.name, block, rows);
1049
0
                        });
1050
0
                continue;
1051
0
            }
1052
27
        } else if (desc.category == ColumnCategory::PARTITION_KEY) {
1053
0
            bool has_partition_value = partition_col_names.contains(desc.name);
1054
0
            bool exists_in_file = ctx->table_info_node->children_column_exists(desc.name);
1055
0
            if (!has_partition_value || exists_in_file) {
1056
0
                ctx->column_names.push_back(desc.name);
1057
0
                continue;
1058
0
            }
1059
0
            has_partition_from_path = true;
1060
27
        } else if (desc.category == ColumnCategory::REGULAR) {
1061
27
            ctx->column_names.push_back(desc.name);
1062
27
        } else if (desc.category == ColumnCategory::GENERATED) {
1063
0
            _init_row_lineage_columns();
1064
0
            if (desc.name == ROW_LINEAGE_ROW_ID) {
1065
0
                ctx->column_names.push_back(desc.name);
1066
0
                this->register_generated_column_handler(
1067
0
                        ROW_LINEAGE_ROW_ID, [this](Block* block, size_t rows) -> Status {
1068
0
                            return _fill_row_lineage_row_id(block, rows);
1069
0
                        });
1070
0
                continue;
1071
0
            } else if (desc.name == ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER) {
1072
0
                ctx->column_names.push_back(desc.name);
1073
0
                this->register_generated_column_handler(
1074
0
                        ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER,
1075
0
                        [this](Block* block, size_t rows) -> Status {
1076
0
                            return _fill_row_lineage_last_updated_sequence_number(block, rows);
1077
0
                        });
1078
0
                continue;
1079
0
            }
1080
0
        }
1081
27
    }
1082
1083
20
    if (has_partition_from_path) {
1084
0
        RETURN_IF_ERROR(_extract_partition_values(*ctx->range, ctx->tuple_descriptor,
1085
0
                                                  _fill_partition_values,
1086
0
                                                  &_fill_partition_value_is_null));
1087
0
    }
1088
1089
20
    _all_required_col_names = ctx->column_names;
1090
1091
    // Create column IDs from ORC type
1092
20
    auto column_id_result =
1093
20
            _create_column_ids(orc_type_ptr, ctx->tuple_descriptor, ctx->table_info_node);
1094
20
    ctx->column_ids = std::move(column_id_result.column_ids);
1095
20
    ctx->filter_column_ids = std::move(column_id_result.filter_column_ids);
1096
1097
    // Build field_id -> block_column_name mapping for equality delete filtering.
1098
27
    for (const auto* slot : ctx->tuple_descriptor->slots()) {
1099
27
        _id_to_block_column_name.emplace(slot->col_unique_id(), slot->col_name());
1100
27
    }
1101
1102
    // Process delete files (must happen before _do_init_reader so expand col IDs are included)
1103
20
    RETURN_IF_ERROR(_init_row_filters());
1104
1105
    // Add expand column IDs for equality delete and remap expand column names
1106
    // (matching master's behavior with __equality_delete_column__ prefix)
1107
20
    const static std::string EQ_DELETE_PRE = "__equality_delete_column__";
1108
20
    bool all_file_columns_have_field_ids = true;
1109
66
    for (uint64_t i = 0; i < orc_type_ptr->getSubtypeCount(); ++i) {
1110
46
        const orc::Type* sub_type = orc_type_ptr->getSubtype(i);
1111
46
        if (!sub_type->hasAttributeKey(ICEBERG_ORC_ATTRIBUTE)) {
1112
16
            all_file_columns_have_field_ids = false;
1113
16
        }
1114
46
    }
1115
20
    const bool use_field_ids_for_hidden_keys =
1116
20
            supports_iceberg_scan_semantics_v1(&get_scan_params())
1117
20
                    ? orc_subtree_has_iceberg_id(orc_type_ptr, ICEBERG_ORC_ATTRIBUTE)
1118
20
                    : all_file_columns_have_field_ids;
1119
20
    const auto find_file_column_by_name = [&](const std::string& name) -> const orc::Type* {
1120
0
        for (uint64_t j = 0; j < orc_type_ptr->getSubtypeCount(); ++j) {
1121
0
            if (iequal(orc_type_ptr->getFieldName(j), name)) {
1122
0
                return orc_type_ptr->getSubtype(j);
1123
0
            }
1124
0
        }
1125
0
        return nullptr;
1126
0
    };
1127
1128
20
    std::vector<std::string> new_expand_col_names;
1129
20
    DORIS_CHECK(_expand_col_names.size() == _expand_col_field_ids.size());
1130
20
    DORIS_CHECK(_expand_col_names.size() == _expand_columns.size());
1131
38
    for (size_t i = 0; i < _expand_col_names.size(); ++i) {
1132
18
        const auto& old_name = _expand_col_names[i];
1133
18
        const int32_t field_id = _expand_col_field_ids[i];
1134
1135
18
        const orc::Type* file_column = nullptr;
1136
18
        OrcEqualityFieldPath file_path;
1137
18
        bool complete_file_path = false;
1138
18
        if (use_field_ids_for_hidden_keys) {
1139
12
            complete_file_path =
1140
12
                    find_orc_equality_field_path_by_id(orc_type_ptr, field_id, &file_path);
1141
12
            if (!complete_file_path && supports_iceberg_scan_semantics_v2(&get_scan_params())) {
1142
6
                const auto table_path = _find_schema_field_path(field_id);
1143
6
                if (!table_path.empty()) {
1144
6
                    complete_file_path = find_orc_equality_field_prefix_by_id_path(
1145
6
                            orc_type_ptr, table_path, &file_path);
1146
6
                }
1147
6
            }
1148
12
            if (!file_path.fields.empty()) {
1149
6
                file_column = file_path.fields.front();
1150
6
            }
1151
12
        } else {
1152
6
            const auto table_path = _find_schema_field_path(field_id);
1153
6
            if (!table_path.empty()) {
1154
6
                complete_file_path = find_orc_equality_field_prefix_by_name_path(
1155
6
                        orc_type_ptr, table_path, old_name, &file_path);
1156
6
                if (!file_path.fields.empty()) {
1157
5
                    file_column = file_path.fields.front();
1158
5
                }
1159
6
            } else {
1160
0
                file_column = find_file_column_by_name(old_name);
1161
0
                complete_file_path = file_column != nullptr;
1162
0
            }
1163
6
        }
1164
1165
18
        std::string file_col_name = old_name;
1166
18
        std::string leaf_name = old_name;
1167
18
        if (!file_path.fields.empty()) {
1168
11
            file_col_name = file_path.names.front();
1169
11
            leaf_name = file_path.names.back();
1170
11
        } else if (file_column != nullptr) {
1171
0
            for (uint64_t j = 0; j < orc_type_ptr->getSubtypeCount(); ++j) {
1172
0
                if (orc_type_ptr->getSubtype(j) == file_column) {
1173
0
                    file_col_name = orc_type_ptr->getFieldName(j);
1174
0
                    leaf_name = file_col_name;
1175
0
                    break;
1176
0
                }
1177
0
            }
1178
0
        }
1179
18
        std::string table_col_name = EQ_DELETE_PRE + std::to_string(field_id) + "_" + leaf_name;
1180
1181
18
        if (field_id >= 0) {
1182
18
            _id_to_block_column_name[field_id] = table_col_name;
1183
18
        }
1184
18
        _expand_columns[i].name = table_col_name;
1185
18
        if (file_column == nullptr) {
1186
7
            RETURN_IF_ERROR(_register_missing_equality_delete_column(field_id, table_col_name,
1187
7
                                                                     _expand_columns[i].type));
1188
            // The old data file predates this equality key. Its logical initial default is appended
1189
            // after the read. Adding it to column_names/table_info_node would mark it as an
1190
            // existing ORC child and make OrcReader read a column that is not present in the file.
1191
7
            new_expand_col_names.push_back(table_col_name);
1192
7
            continue;
1193
7
        }
1194
11
        new_expand_col_names.push_back(table_col_name);
1195
1196
11
        if (!complete_file_path) {
1197
1
            ColumnPtr missing_value;
1198
1
            RETURN_IF_ERROR(_create_missing_equality_delete_value(
1199
1
                    field_id, _expand_columns[i].type, file_path.fields.size(), &missing_value));
1200
1
            _nested_equality_delete_columns.push_back({
1201
1
                    .field_id = field_id,
1202
1
                    .block_name = table_col_name,
1203
1
                    .leaf_type = _expand_columns[i].type,
1204
1
                    .child_indexes = file_path.child_indexes,
1205
1
                    .missing_value = std::move(missing_value),
1206
1
            });
1207
1
            _expand_columns[i].type = make_nullable(convert_to_doris_type(file_column));
1208
1
            _expand_columns[i].column = _expand_columns[i].type->create_column();
1209
10
        } else if (!file_path.child_indexes.empty()) {
1210
8
            _nested_equality_delete_columns.push_back({
1211
8
                    .field_id = field_id,
1212
8
                    .block_name = table_col_name,
1213
8
                    .leaf_type = _expand_columns[i].type,
1214
8
                    .child_indexes = file_path.child_indexes,
1215
8
                    .missing_value = nullptr,
1216
8
            });
1217
8
            _expand_columns[i].type = make_nullable(convert_to_doris_type(file_column));
1218
8
            _expand_columns[i].column = _expand_columns[i].type->create_column();
1219
8
        }
1220
1221
11
        for (uint64_t column_id = file_column->getColumnId();
1222
31
             column_id <= file_column->getMaximumColumnId(); ++column_id) {
1223
20
            ctx->column_ids.insert(column_id);
1224
20
        }
1225
1226
11
        ctx->column_names.push_back(table_col_name);
1227
11
        ctx->table_info_node->add_children(table_col_name, file_col_name,
1228
11
                                           TableSchemaChangeHelper::ConstNode::get_instance());
1229
11
    }
1230
20
    _expand_col_names = std::move(new_expand_col_names);
1231
1232
20
    return Status::OK();
1233
20
}
1234
1235
// ============================================================================
1236
// IcebergOrcReader: _create_column_ids
1237
// ============================================================================
1238
ColumnIdResult IcebergOrcReader::_create_column_ids(
1239
        const orc::Type* orc_type, const TupleDescriptor* tuple_descriptor,
1240
27
        const std::shared_ptr<TableSchemaChangeHelper::Node>& table_info_node) {
1241
27
    std::unordered_map<int, const orc::Type*> iceberg_id_to_orc_type_map;
1242
123
    for (uint64_t i = 0; i < orc_type->getSubtypeCount(); ++i) {
1243
96
        const auto* orc_sub_type = orc_type->getSubtype(i);
1244
96
        if (!orc_sub_type) {
1245
0
            continue;
1246
0
        }
1247
96
        if (!orc_sub_type->hasAttributeKey(ICEBERG_ORC_ATTRIBUTE)) {
1248
17
            continue;
1249
17
        }
1250
79
        int iceberg_id = std::stoi(orc_sub_type->getAttributeValue(ICEBERG_ORC_ATTRIBUTE));
1251
79
        iceberg_id_to_orc_type_map[iceberg_id] = orc_sub_type;
1252
79
    }
1253
1254
27
    std::set<uint64_t> column_ids;
1255
27
    std::set<uint64_t> filter_column_ids;
1256
1257
27
    auto process_access_paths = [](const orc::Type* orc_field,
1258
27
                                   const std::vector<TColumnAccessPath>& access_paths,
1259
27
                                   std::set<uint64_t>& out_ids) {
1260
19
        process_nested_access_paths(
1261
19
                orc_field, access_paths, out_ids,
1262
19
                [](const orc::Type* type) { return type->getColumnId(); },
1263
19
                [](const orc::Type* type) { return type->getMaximumColumnId(); },
1264
19
                IcebergOrcNestedColumnUtils::extract_nested_column_ids);
1265
19
    };
1266
1267
    // The Iceberg schema-mapping root is a StructNode whose registered children are the real
1268
    // table columns. When present, resolve each column by name through it so the column-id set
1269
    // stays consistent with the schema-mapping decision (BY_ID or BY_NAME/name-mapping);
1270
    // otherwise fall back to matching by Iceberg field id.
1271
27
    const auto* struct_node =
1272
27
            dynamic_cast<const TableSchemaChangeHelper::StructNode*>(table_info_node.get());
1273
1274
42
    for (const auto* slot : tuple_descriptor->slots()) {
1275
42
        const orc::Type* orc_field = nullptr;
1276
42
        if (struct_node != nullptr) {
1277
            // Synthesized/metadata slots (e.g. the TopN global row-id or the $row_id column) are
1278
            // never registered as children, so check membership before querying: calling
1279
            // children_column_exists() on an unregistered name DCHECK-aborts in debug builds and
1280
            // throws std::out_of_range from .at() in release builds.
1281
29
            if (struct_node->get_children().contains(slot->col_name()) &&
1282
29
                struct_node->children_column_exists(slot->col_name())) {
1283
                // Select the physical child resolved by the shared schema-mapping pass. Hidden
1284
                // equality keys and projected columns must obey the same BY_NAME decision for
1285
                // partial-id ORC files.
1286
27
                const auto& file_column_name =
1287
27
                        struct_node->children_file_column_name(slot->col_name());
1288
35
                for (uint64_t i = 0; i < orc_type->getSubtypeCount(); ++i) {
1289
35
                    if (orc_type->getFieldName(i) == file_column_name) {
1290
27
                        orc_field = orc_type->getSubtype(i);
1291
27
                        break;
1292
27
                    }
1293
35
                }
1294
27
                DORIS_CHECK(orc_field != nullptr);
1295
27
            }
1296
29
        } else {
1297
13
            auto it = iceberg_id_to_orc_type_map.find(slot->col_unique_id());
1298
13
            if (it != iceberg_id_to_orc_type_map.end()) {
1299
13
                orc_field = it->second;
1300
13
            }
1301
13
        }
1302
42
        if (orc_field == nullptr) {
1303
2
            continue;
1304
2
        }
1305
1306
40
        if ((slot->col_type() != TYPE_STRUCT && slot->col_type() != TYPE_ARRAY &&
1307
40
             slot->col_type() != TYPE_MAP)) {
1308
27
            column_ids.insert(orc_field->getColumnId());
1309
27
            if (slot->is_predicate()) {
1310
0
                filter_column_ids.insert(orc_field->getColumnId());
1311
0
            }
1312
27
            continue;
1313
27
        }
1314
1315
13
        const auto& all_access_paths = slot->all_access_paths();
1316
13
        process_access_paths(orc_field, all_access_paths, column_ids);
1317
1318
13
        const auto& predicate_access_paths = slot->predicate_access_paths();
1319
13
        if (!predicate_access_paths.empty()) {
1320
6
            process_access_paths(orc_field, predicate_access_paths, filter_column_ids);
1321
6
        }
1322
13
    }
1323
1324
27
    return {std::move(column_ids), std::move(filter_column_ids)};
1325
27
}
1326
1327
// ============================================================================
1328
// IcebergOrcReader: _read_position_delete_file
1329
// ============================================================================
1330
Status IcebergOrcReader::_read_position_delete_file(const TFileRangeDesc* delete_range,
1331
0
                                                    DeleteFile* position_delete) {
1332
0
    OrcReader orc_delete_reader(get_profile(), get_state(), get_scan_params(), *delete_range,
1333
0
                                READ_DELETE_FILE_BATCH_SIZE, get_state()->timezone(), get_io_ctx(),
1334
0
                                _meta_cache);
1335
0
    OrcInitContext delete_ctx;
1336
0
    delete_ctx.column_names = delete_file_col_names;
1337
0
    delete_ctx.col_name_to_block_idx =
1338
0
            const_cast<std::unordered_map<std::string, uint32_t>*>(&DELETE_COL_NAME_TO_BLOCK_IDX);
1339
0
    RETURN_IF_ERROR(orc_delete_reader.init_reader(&delete_ctx));
1340
1341
0
    bool eof = false;
1342
0
    DataTypePtr data_type_file_path {new DataTypeString};
1343
0
    DataTypePtr data_type_pos {new DataTypeInt64};
1344
0
    while (!eof) {
1345
0
        Block block = {{data_type_file_path, ICEBERG_FILE_PATH}, {data_type_pos, ICEBERG_ROW_POS}};
1346
1347
0
        size_t read_rows = 0;
1348
0
        RETURN_IF_ERROR(orc_delete_reader.get_next_block(&block, &read_rows, &eof));
1349
1350
0
        RETURN_IF_ERROR(_gen_position_delete_file_range(block, position_delete, read_rows, false));
1351
0
    }
1352
0
    return Status::OK();
1353
0
}
1354
1355
} // namespace doris