Coverage Report

Created: 2026-08-05 20:10

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