Coverage Report

Created: 2026-07-27 18:41

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format_v2/column_mapper.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_v2/column_mapper.h"
19
20
#include <algorithm>
21
#include <cstddef>
22
#include <memory>
23
#include <optional>
24
#include <set>
25
#include <sstream>
26
#include <string_view>
27
#include <utility>
28
#include <vector>
29
30
#include "common/consts.h"
31
#include "common/exception.h"
32
#include "common/status.h"
33
#include "core/data_type/convert_field_to_type.h"
34
#include "core/data_type/data_type_array.h"
35
#include "core/data_type/data_type_map.h"
36
#include "core/data_type/data_type_nullable.h"
37
#include "core/data_type/data_type_string.h"
38
#include "core/data_type/data_type_struct.h"
39
#include "core/data_type/primitive_type.h"
40
#include "exprs/runtime_filter_expr.h"
41
#include "exprs/short_circuit_evaluation_expr.h"
42
#include "exprs/vcase_expr.h"
43
#include "exprs/vcast_expr.h"
44
#include "exprs/vcondition_expr.h"
45
#include "exprs/vectorized_fn_call.h"
46
#include "exprs/vexpr_context.h"
47
#include "exprs/vin_predicate.h"
48
#include "exprs/vliteral.h"
49
#include "format_v2/column_mapper_nested.h"
50
#include "format_v2/expr/cast.h"
51
#include "format_v2/file_reader.h"
52
#include "format_v2/schema_projection.h"
53
#include "format_v2/table_reader.h"
54
#include "gen_cpp/Exprs_types.h"
55
56
namespace doris::format {
57
58
namespace {
59
60
10
bool has_shared_descendant_field_id(const ColumnDefinition& table, const ColumnDefinition& file) {
61
10
    const auto& table_children =
62
10
            table.identity_children.empty() ? table.children : table.identity_children;
63
10
    for (const auto& table_child : table_children) {
64
10
        if (!table_child.has_identifier_field_id()) {
65
0
            continue;
66
0
        }
67
10
        const auto file_child =
68
10
                std::ranges::find_if(file.children, [&](const ColumnDefinition& candidate) {
69
10
                    return candidate.has_identifier_field_id() &&
70
10
                           candidate.get_identifier_field_id() ==
71
9
                                   table_child.get_identifier_field_id();
72
10
                });
73
10
        if (file_child != file.children.end() ||
74
10
            std::ranges::any_of(file.children, [&](const ColumnDefinition& candidate) {
75
2
                return has_shared_descendant_field_id(table_child, candidate);
76
9
            })) {
77
9
            return true;
78
9
        }
79
10
    }
80
1
    return false;
81
10
}
82
83
16
std::string mapping_mode_to_string(TableColumnMappingMode mode) {
84
16
    switch (mode) {
85
1
    case TableColumnMappingMode::BY_FIELD_ID:
86
1
        return "BY_FIELD_ID";
87
14
    case TableColumnMappingMode::BY_NAME:
88
14
        return "BY_NAME";
89
1
    case TableColumnMappingMode::BY_INDEX:
90
1
        return "BY_INDEX";
91
16
    }
92
0
    return "UNKNOWN";
93
16
}
94
95
13.0M
bool column_has_name(const ColumnDefinition& column, const std::string& name) {
96
13.0M
    if (to_lower(column.name) == to_lower(name)) {
97
299k
        return true;
98
299k
    }
99
12.7M
    if (column.has_identifier_name() && to_lower(column.get_identifier_name()) == to_lower(name)) {
100
0
        return true;
101
0
    }
102
12.7M
    return std::ranges::any_of(column.name_mapping, [&](const std::string& alias) {
103
146
        return to_lower(alias) == to_lower(name);
104
146
    });
105
12.7M
}
106
107
6.83M
bool column_names_match(const ColumnDefinition& lhs, const ColumnDefinition& rhs) {
108
6.83M
    if (!lhs.has_name_mapping) {
109
6.83M
        if (column_has_name(rhs, lhs.name)) {
110
299k
            return true;
111
299k
        }
112
6.53M
        if (lhs.has_identifier_name() && column_has_name(rhs, lhs.get_identifier_name())) {
113
1
            return true;
114
1
        }
115
6.53M
    }
116
    // Explicit Iceberg name mapping is authoritative: an empty alias list represents a field that
117
    // did not exist in the imported file, so only transported aliases may match.
118
6.53M
    return std::ranges::any_of(lhs.name_mapping, [&](const std::string& alias) {
119
24
        return column_has_name(rhs, alias);
120
24
    });
121
6.83M
}
122
123
class ColumnMatcher {
124
public:
125
3
    virtual ~ColumnMatcher() = default;
126
    virtual const ColumnDefinition* find(
127
            const ColumnDefinition& table_column,
128
            const std::vector<ColumnDefinition>& file_schema) const = 0;
129
};
130
131
class FieldIdMatcher final : public ColumnMatcher {
132
public:
133
    const ColumnDefinition* find(const ColumnDefinition& table_column,
134
268k
                                 const std::vector<ColumnDefinition>& file_schema) const override {
135
268k
        if (!table_column.has_identifier_field_id()) {
136
555
            return nullptr;
137
555
        }
138
268k
        const auto field_id = table_column.get_identifier_field_id();
139
2.21M
        const auto field_it = std::ranges::find_if(file_schema, [&](const ColumnDefinition& field) {
140
2.21M
            return field.has_identifier_field_id() && field.get_identifier_field_id() == field_id;
141
2.21M
        });
142
268k
        return field_it == file_schema.end() ? nullptr : &*field_it;
143
268k
    }
144
};
145
146
class NameMatcher final : public ColumnMatcher {
147
public:
148
    const ColumnDefinition* find(const ColumnDefinition& table_column,
149
300k
                                 const std::vector<ColumnDefinition>& file_schema) const override {
150
6.83M
        const auto field_it = std::ranges::find_if(file_schema, [&](const ColumnDefinition& field) {
151
6.83M
            return column_names_match(table_column, field);
152
6.83M
        });
153
300k
        return field_it == file_schema.end() ? nullptr : &*field_it;
154
300k
    }
155
};
156
157
class PositionMatcher final : public ColumnMatcher {
158
public:
159
    const ColumnDefinition* find(const ColumnDefinition& table_column,
160
2
                                 const std::vector<ColumnDefinition>& file_schema) const override {
161
2
        if (!table_column.has_identifier_field_id()) {
162
2
            return nullptr;
163
2
        }
164
0
        const auto position = table_column.get_identifier_position();
165
0
        if (position < 0 || static_cast<size_t>(position) >= file_schema.size()) {
166
0
            return nullptr;
167
0
        }
168
0
        return &file_schema[static_cast<size_t>(position)];
169
0
    }
170
};
171
172
569k
const ColumnMatcher& matcher_for_mode(TableColumnMappingMode mode) {
173
569k
    static const FieldIdMatcher field_id_matcher;
174
569k
    static const NameMatcher name_matcher;
175
569k
    static const PositionMatcher position_matcher;
176
569k
    switch (mode) {
177
268k
    case TableColumnMappingMode::BY_FIELD_ID:
178
268k
        return field_id_matcher;
179
300k
    case TableColumnMappingMode::BY_NAME:
180
300k
        return name_matcher;
181
2
    case TableColumnMappingMode::BY_INDEX:
182
2
        return position_matcher;
183
569k
    }
184
0
    return field_id_matcher;
185
569k
}
186
187
12
std::string virtual_column_type_to_string(TableVirtualColumnType type) {
188
12
    switch (type) {
189
9
    case TableVirtualColumnType::INVALID:
190
9
        return "INVALID";
191
1
    case TableVirtualColumnType::ROW_ID:
192
1
        return "ROW_ID";
193
1
    case TableVirtualColumnType::LAST_UPDATED_SEQUENCE_NUMBER:
194
1
        return "LAST_UPDATED_SEQUENCE_NUMBER";
195
1
    case TableVirtualColumnType::ICEBERG_ROWID:
196
1
        return "ICEBERG_ROWID";
197
12
    }
198
0
    return "UNKNOWN";
199
12
}
200
201
12
std::string filter_conversion_type_to_string(FilterConversionType type) {
202
12
    switch (type) {
203
3
    case FilterConversionType::COPY_DIRECTLY:
204
3
        return "COPY_DIRECTLY";
205
1
    case FilterConversionType::CAST_FILTER:
206
1
        return "CAST_FILTER";
207
1
    case FilterConversionType::READER_EXPRESSION:
208
1
        return "READER_EXPRESSION";
209
6
    case FilterConversionType::FINALIZE_ONLY:
210
6
        return "FINALIZE_ONLY";
211
1
    case FilterConversionType::CONSTANT:
212
1
        return "CONSTANT";
213
12
    }
214
0
    return "UNKNOWN";
215
12
}
216
217
47
std::string data_type_debug_string(const DataTypePtr& type) {
218
47
    return type == nullptr ? "null" : type->get_name();
219
47
}
220
221
11
std::string field_debug_string(const Field& field) {
222
11
    std::ostringstream out;
223
11
    out << "Field{type=" << type_to_string(field.get_type()) << ", value=";
224
11
    switch (field.get_type()) {
225
0
    case TYPE_NULL:
226
0
        out << "null";
227
0
        break;
228
9
    case TYPE_INT:
229
9
        out << field.get<TYPE_INT>();
230
9
        break;
231
0
    case TYPE_BIGINT:
232
0
        out << field.get<TYPE_BIGINT>();
233
0
        break;
234
2
    case TYPE_STRING:
235
2
        out << field.get<TYPE_STRING>();
236
2
        break;
237
0
    default:
238
0
        out << field.to_debug_string(0);
239
0
        break;
240
11
    }
241
11
    out << "}";
242
11
    return out.str();
243
11
}
244
245
template <typename T, typename Formatter>
246
61
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
247
61
    std::ostringstream out;
248
61
    out << "[";
249
83
    for (size_t i = 0; i < values.size(); ++i) {
250
22
        if (i > 0) {
251
1
            out << ", ";
252
1
        }
253
22
        out << formatter(values[i]);
254
22
    }
255
61
    out << "]";
256
61
    return out.str();
257
61
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEZNKS0_16ColumnDefinition12debug_stringEvE3$_0EES8_RKSt6vectorIT_SaISC_EET0_
Line
Count
Source
246
11
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
247
11
    std::ostringstream out;
248
11
    out << "[";
249
19
    for (size_t i = 0; i < values.size(); ++i) {
250
8
        if (i > 0) {
251
0
            out << ", ";
252
0
        }
253
8
        out << formatter(values[i]);
254
8
    }
255
11
    out << "]";
256
11
    return out.str();
257
11
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_16ColumnDefinitionEZNKS3_12debug_stringB5cxx11EvE3$_1EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISC_EET0_
Line
Count
Source
246
11
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
247
11
    std::ostringstream out;
248
11
    out << "[";
249
12
    for (size_t i = 0; i < values.size(); ++i) {
250
1
        if (i > 0) {
251
0
            out << ", ";
252
0
        }
253
1
        out << formatter(values[i]);
254
1
    }
255
11
    out << "]";
256
11
    return out.str();
257
11
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_16ColumnDefinitionEZNKS3_12debug_stringB5cxx11EvE3$_2EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISC_EET0_
Line
Count
Source
246
11
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
247
11
    std::ostringstream out;
248
11
    out << "[";
249
11
    for (size_t i = 0; i < values.size(); ++i) {
250
0
        if (i > 0) {
251
0
            out << ", ";
252
0
        }
253
0
        out << formatter(values[i]);
254
0
    }
255
11
    out << "]";
256
11
    return out.str();
257
11
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_16LocalColumnIndexEZNKS3_12debug_stringB5cxx11EvE3$_0EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISC_EET0_
Line
Count
Source
246
2
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
247
2
    std::ostringstream out;
248
2
    out << "[";
249
3
    for (size_t i = 0; i < values.size(); ++i) {
250
1
        if (i > 0) {
251
0
            out << ", ";
252
0
        }
253
1
        out << formatter(values[i]);
254
1
    }
255
2
    out << "]";
256
2
    return out.str();
257
2
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_16ColumnDefinitionEZNKS0_13ColumnMapping12debug_stringB5cxx11EvE3$_0EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
246
12
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
247
12
    std::ostringstream out;
248
12
    out << "[";
249
17
    for (size_t i = 0; i < values.size(); ++i) {
250
5
        if (i > 0) {
251
0
            out << ", ";
252
0
        }
253
5
        out << formatter(values[i]);
254
5
    }
255
12
    out << "]";
256
12
    return out.str();
257
12
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_13ColumnMappingEZNKS3_12debug_stringB5cxx11EvE3$_1EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISC_EET0_
Line
Count
Source
246
12
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
247
12
    std::ostringstream out;
248
12
    out << "[";
249
17
    for (size_t i = 0; i < values.size(); ++i) {
250
5
        if (i > 0) {
251
0
            out << ", ";
252
0
        }
253
5
        out << formatter(values[i]);
254
5
    }
255
12
    out << "]";
256
12
    return out.str();
257
12
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_13ColumnMappingEZNKS0_17TableColumnMapper12debug_stringB5cxx11EvE3$_0EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
246
1
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
247
1
    std::ostringstream out;
248
1
    out << "[";
249
3
    for (size_t i = 0; i < values.size(); ++i) {
250
2
        if (i > 0) {
251
1
            out << ", ";
252
1
        }
253
2
        out << formatter(values[i]);
254
2
    }
255
1
    out << "]";
256
1
    return out.str();
257
1
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_13ColumnMappingEZNKS0_17TableColumnMapper12debug_stringB5cxx11EvE3$_1EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
246
1
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
247
1
    std::ostringstream out;
248
1
    out << "[";
249
1
    for (size_t i = 0; i < values.size(); ++i) {
250
0
        if (i > 0) {
251
0
            out << ", ";
252
0
        }
253
0
        out << formatter(values[i]);
254
0
    }
255
1
    out << "]";
256
1
    return out.str();
257
1
}
258
259
} // namespace
260
261
const ColumnDefinition* find_column_by_name(const ColumnDefinition& table_column,
262
10
                                            const std::vector<ColumnDefinition>& file_schema) {
263
10
    return matcher_for_mode(TableColumnMappingMode::BY_NAME).find(table_column, file_schema);
264
10
}
265
266
const Field* find_partition_value(const ColumnDefinition& table_column,
267
543k
                                  const std::map<std::string, Field>& partition_values) {
268
800k
    const auto find_by_name = [&](const std::string& name) -> const Field* {
269
800k
        const auto value_it = partition_values.find(name);
270
800k
        return value_it == partition_values.end() ? nullptr : &value_it->second;
271
800k
    };
272
543k
    if (const auto* value = find_by_name(table_column.name); value != nullptr) {
273
25.0k
        return value;
274
25.0k
    }
275
518k
    if (table_column.has_identifier_name()) {
276
258k
        if (const auto* value = find_by_name(table_column.get_identifier_name());
277
258k
            value != nullptr) {
278
0
            return value;
279
0
        }
280
258k
    }
281
518k
    for (const auto& alias : table_column.name_mapping) {
282
24
        if (const auto* value = find_by_name(alias); value != nullptr) {
283
1
            return value;
284
1
        }
285
24
    }
286
518k
    return nullptr;
287
518k
}
288
289
struct FileSlotRewriteInfo {
290
    size_t block_position = 0;
291
    DataTypePtr file_type;
292
    DataTypePtr table_type;
293
    std::string file_column_name;
294
};
295
296
struct RewriteContext {
297
    RuntimeState* runtime_state = nullptr;
298
    std::vector<VExprSPtr> created_exprs {};
299
300
127k
    void add_created_expr(VExprSPtr expr) { created_exprs.push_back(std::move(expr)); }
301
302
72.1k
    Status prepare_created_exprs(VExprContext* context) const {
303
72.1k
        DORIS_CHECK(context != nullptr);
304
72.1k
        RowDescriptor row_desc;
305
126k
        for (const auto& expr : created_exprs) {
306
126k
            if (dynamic_cast<const Cast*>(expr.get()) != nullptr && runtime_state == nullptr) {
307
0
                return Status::InvalidArgument(
308
0
                        "RuntimeState is required to prepare rewritten cast expression {}",
309
0
                        expr->expr_name());
310
0
            }
311
126k
            RETURN_IF_ERROR(expr->prepare(runtime_state, row_desc, context));
312
126k
        }
313
72.1k
        return Status::OK();
314
72.1k
    }
315
};
316
317
static VExprSPtr create_file_slot_ref(const VSlotRef& slot_ref,
318
                                      const FileSlotRewriteInfo& rewrite_info,
319
73.9k
                                      RewriteContext* rewrite_context) {
320
73.9k
    auto ref =
321
73.9k
            VSlotRef::create_shared(slot_ref.slot_id(), cast_set<int>(rewrite_info.block_position),
322
73.9k
                                    -1, rewrite_info.file_type, rewrite_info.file_column_name);
323
73.9k
    rewrite_context->add_created_expr(ref);
324
73.9k
    return ref;
325
73.9k
}
326
327
172k
static bool is_cast_expr(const VExprSPtr& expr) {
328
172k
    return dynamic_cast<const Cast*>(expr.get()) != nullptr;
329
172k
}
330
331
202k
static bool is_binary_comparison_predicate(const VExprSPtr& expr) {
332
203k
    if (expr == nullptr || expr->get_num_children() != 2 ||
333
202k
        (expr->node_type() != TExprNodeType::BINARY_PRED &&
334
141k
         expr->node_type() != TExprNodeType::NULL_AWARE_BINARY_PRED)) {
335
141k
        return false;
336
141k
    }
337
61.1k
    switch (expr->op()) {
338
14.0k
    case TExprOpcode::EQ:
339
14.0k
    case TExprOpcode::EQ_FOR_NULL:
340
15.9k
    case TExprOpcode::NE:
341
18.5k
    case TExprOpcode::GE:
342
57.4k
    case TExprOpcode::GT:
343
59.3k
    case TExprOpcode::LE:
344
61.1k
    case TExprOpcode::LT:
345
61.1k
        return true;
346
0
    default:
347
0
        return false;
348
61.1k
    }
349
61.1k
}
350
351
16
std::string TableColumnMapperOptions::debug_string() const {
352
16
    std::ostringstream out;
353
16
    out << "TableColumnMapperOptions{mode=" << mapping_mode_to_string(mode)
354
16
        << ", reject_missing_required_field=" << reject_missing_required_field
355
16
        << ", allow_idless_complex_wrapper_projection=" << allow_idless_complex_wrapper_projection
356
16
        << ", enable_row_lineage_virtual_columns=" << enable_row_lineage_virtual_columns << "}";
357
16
    return out.str();
358
16
}
359
360
11
std::string ColumnDefinition::debug_string() const {
361
11
    std::ostringstream out;
362
11
    out << "ColumnDefinition{name=" << name << ", identifier=" << field_debug_string(identifier)
363
11
        << ", name_mapping="
364
11
        << join_debug_strings(name_mapping, [](const std::string& name) { return name; })
365
11
        << ", has_name_mapping=" << has_name_mapping << ", local_id=" << local_id
366
11
        << ", type=" << data_type_debug_string(type) << ", children="
367
11
        << join_debug_strings(children,
368
11
                              [](const ColumnDefinition& child) { return child.debug_string(); })
369
11
        << ", identity_children="
370
11
        << join_debug_strings(identity_children,
371
11
                              [](const ColumnDefinition& child) { return child.debug_string(); })
372
11
        << ", has_default_expr=" << (default_expr != nullptr)
373
11
        << ", has_initial_default=" << initial_default_value.has_value() << ", is_optional=";
374
11
    if (is_optional.has_value()) {
375
0
        out << *is_optional;
376
11
    } else {
377
11
        out << "unknown";
378
11
    }
379
11
    out << ", is_partition_key=" << is_partition_key << "}";
380
11
    return out.str();
381
11
}
382
383
2
std::string LocalColumnIndex::debug_string() const {
384
2
    std::ostringstream out;
385
2
    out << "LocalColumnIndex{index=" << index << ", project_all_children=" << project_all_children
386
2
        << ", children="
387
2
        << join_debug_strings(children,
388
2
                              [](const LocalColumnIndex& child) { return child.debug_string(); })
389
2
        << "}";
390
2
    return out.str();
391
2
}
392
393
12
std::string ColumnMapping::debug_string() const {
394
12
    std::ostringstream out;
395
12
    out << "ColumnMapping{global_index=" << global_index
396
12
        << ", table_column_name=" << table_column_name << ", file_local_id=";
397
12
    if (file_local_id.has_value()) {
398
7
        out << *file_local_id;
399
7
    } else {
400
5
        out << "null";
401
5
    }
402
12
    out << ", constant_index=";
403
12
    if (constant_index.has_value()) {
404
5
        out << *constant_index;
405
7
    } else {
406
7
        out << "null";
407
7
    }
408
12
    out << ", file_column_name=" << file_column_name
409
12
        << ", original_file_type=" << data_type_debug_string(original_file_type)
410
12
        << ", original_file_children="
411
12
        << join_debug_strings(original_file_children,
412
12
                              [](const ColumnDefinition& child) { return child.debug_string(); })
413
12
        << ", file_type=" << data_type_debug_string(file_type)
414
12
        << ", table_type=" << data_type_debug_string(table_type)
415
12
        << ", has_projection=" << (projection != nullptr) << ", child_mappings="
416
12
        << join_debug_strings(child_mappings,
417
12
                              [](const ColumnMapping& child) { return child.debug_string(); })
418
12
        << ", is_trivial=" << is_trivial << ", is_constant=" << constant_index.has_value()
419
12
        << ", filter_conversion=" << filter_conversion_type_to_string(filter_conversion)
420
12
        << ", virtual_column_type=" << virtual_column_type_to_string(virtual_column_type)
421
12
        << ", has_default_expr=" << (default_expr != nullptr) << "}";
422
12
    return out.str();
423
12
}
424
425
1
std::string TableColumnMapper::debug_string() const {
426
1
    std::ostringstream out;
427
1
    out << "TableColumnMapper{options=" << _options.debug_string() << ", mappings="
428
1
        << join_debug_strings(_mappings,
429
2
                              [](const ColumnMapping& mapping) { return mapping.debug_string(); })
430
1
        << ", hidden_mappings="
431
1
        << join_debug_strings(_hidden_mappings,
432
1
                              [](const ColumnMapping& mapping) { return mapping.debug_string(); })
433
1
        << ", constant_count=" << _constant_map.size() << "}";
434
1
    return out.str();
435
1
}
436
437
static const FileSlotRewriteInfo* find_slot_rewrite_info(
438
        const VExprSPtr& expr,
439
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
440
61.9k
        const VSlotRef** slot_ref) {
441
61.9k
    if (expr == nullptr) {
442
0
        return nullptr;
443
0
    }
444
61.9k
    VExprSPtr slot_expr = expr;
445
61.9k
    const bool input_is_cast = is_cast_expr(expr) && expr->get_num_children() == 1;
446
61.9k
    if (is_cast_expr(expr) && expr->get_num_children() == 1) {
447
462
        slot_expr = expr->children()[0];
448
462
    }
449
61.9k
    if (!slot_expr->is_slot_ref()) {
450
13.6k
        return nullptr;
451
13.6k
    }
452
48.3k
    const auto* candidate_slot_ref = assert_cast<const VSlotRef*>(slot_expr.get());
453
48.3k
    const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*candidate_slot_ref));
454
48.3k
    if (rewrite_it == global_to_file_slot.end()) {
455
0
        return nullptr;
456
0
    }
457
48.3k
    if (input_is_cast && !expr->data_type()->equals(*rewrite_it->second.table_type)) {
458
426
        return nullptr;
459
426
    }
460
47.8k
    if (slot_ref != nullptr) {
461
47.8k
        *slot_ref = candidate_slot_ref;
462
47.8k
    }
463
47.8k
    return &rewrite_it->second;
464
48.3k
}
465
466
722k
static bool filter_conversion_has_local_source(FilterConversionType conversion) {
467
722k
    switch (conversion) {
468
679k
    case FilterConversionType::COPY_DIRECTLY:
469
703k
    case FilterConversionType::CAST_FILTER:
470
719k
    case FilterConversionType::READER_EXPRESSION:
471
719k
        return true;
472
2.27k
    case FilterConversionType::FINALIZE_ONLY:
473
2.27k
    case FilterConversionType::CONSTANT:
474
2.27k
        return false;
475
722k
    }
476
0
    return false;
477
722k
}
478
479
static bool table_filter_has_only_local_entries(
480
82.9k
        const TableFilter& table_filter, const std::map<GlobalIndex, FilterEntry>& filter_entries) {
481
83.8k
    for (const auto global_index : table_filter.global_indices) {
482
83.8k
        const auto entry_it = filter_entries.find(global_index);
483
83.9k
        if (entry_it == filter_entries.end() || !entry_it->second.is_local()) {
484
8.15k
            return false;
485
8.15k
        }
486
83.8k
    }
487
74.7k
    return true;
488
82.9k
}
489
490
static VExprSPtr unwrap_literal_for_file_cast(const VExprSPtr& expr,
491
53.5k
                                              const DataTypePtr& table_type) {
492
53.5k
    if (expr == nullptr) {
493
0
        return nullptr;
494
0
    }
495
53.5k
    if (expr->is_literal()) {
496
53.5k
        return expr;
497
53.5k
    }
498
16
    if (is_cast_expr(expr) && expr->get_num_children() == 1 && expr->children()[0]->is_literal() &&
499
16
        expr->children()[0]->data_type()->equals(*table_type)) {
500
0
        return expr->children()[0];
501
0
    }
502
16
    return nullptr;
503
16
}
504
505
0
static Field literal_field_from_expr(const VExpr& literal_expr) {
506
0
    DORIS_CHECK(literal_expr.is_literal());
507
0
    const auto* literal = dynamic_cast<const VLiteral*>(&literal_expr);
508
0
    DORIS_CHECK(literal != nullptr);
509
0
    Field field;
510
0
    literal->get_column_ptr()->get(0, field);
511
0
    return field;
512
0
}
513
514
// Table filter localization clones an already-prepared table expr and then rewrites it to file
515
// slots. Only split-local literals and BE cast nodes need table-reader-specific clone behavior;
516
// plain slot refs and literals use their own VExpr::clone_node().
517
1.08M
static Status clone_table_expr_node(const VExpr& expr, VExprSPtr* cloned_expr) {
518
1.08M
    DORIS_CHECK(cloned_expr != nullptr);
519
1.08M
    if (const auto* split_literal = dynamic_cast<const SplitLocalFileLiteral*>(&expr)) {
520
0
        *cloned_expr = std::make_shared<SplitLocalFileLiteral>(
521
0
                split_literal->data_type(), literal_field_from_expr(expr),
522
0
                split_literal->original_type(), split_literal->original_field());
523
1.08M
    } else if (const auto* vcast_expr = dynamic_cast<const VCastExpr*>(&expr);
524
1.08M
               vcast_expr != nullptr && vcast_expr->node_type() == TExprNodeType::CAST_EXPR) {
525
6.88k
        *cloned_expr = Cast::create_shared(vcast_expr->data_type());
526
6.88k
    }
527
1.08M
    return Status::OK();
528
1.08M
}
529
530
363k
Status clone_table_expr_tree(const VExprSPtr& expr, VExprSPtr* cloned_expr) {
531
363k
    DORIS_CHECK(cloned_expr != nullptr);
532
363k
    if (expr == nullptr) {
533
0
        *cloned_expr = nullptr;
534
0
        return Status::OK();
535
0
    }
536
363k
    return expr->deep_clone(cloned_expr, clone_table_expr_node);
537
363k
}
538
539
static VExprSPtr original_table_literal(const VExprSPtr& literal_expr,
540
53.5k
                                        RewriteContext* rewrite_context = nullptr) {
541
53.5k
    DORIS_CHECK(literal_expr != nullptr);
542
53.5k
    DORIS_CHECK(literal_expr->is_literal());
543
53.5k
    const auto* rewritten_literal = dynamic_cast<const SplitLocalFileLiteral*>(literal_expr.get());
544
53.5k
    if (rewritten_literal == nullptr) {
545
53.5k
        return literal_expr;
546
53.5k
    }
547
2
    auto literal = VLiteral::create_shared(rewritten_literal->original_type(),
548
2
                                           rewritten_literal->original_field());
549
2
    if (rewrite_context != nullptr) {
550
0
        rewrite_context->add_created_expr(literal);
551
0
    }
552
2
    return literal;
553
53.5k
}
554
555
84.6k
static ColumnDefinition hidden_column_from_slot_ref(const VSlotRef& slot_ref) {
556
84.6k
    ColumnDefinition column;
557
84.6k
    column.name = slot_ref.column_name();
558
84.6k
    column.identifier = Field::create_field<TYPE_STRING>(column.name);
559
84.6k
    column.type = slot_ref.data_type();
560
84.6k
    return column;
561
84.6k
}
562
563
static void collect_top_level_slot_columns(const VExprSPtr& expr,
564
260k
                                           std::map<GlobalIndex, ColumnDefinition>* columns) {
565
260k
    DORIS_CHECK(columns != nullptr);
566
260k
    if (expr == nullptr) {
567
0
        return;
568
0
    }
569
260k
    if (expr->is_slot_ref()) {
570
84.6k
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
571
84.6k
        columns->try_emplace(slot_ref_global_index(*slot_ref),
572
84.6k
                             hidden_column_from_slot_ref(*slot_ref));
573
84.6k
        return;
574
84.6k
    }
575
177k
    for (const auto& child : expr->children()) {
576
177k
        collect_top_level_slot_columns(child, columns);
577
177k
    }
578
175k
}
579
580
488
static std::optional<uint8_t> signed_integer_width(PrimitiveType type) {
581
488
    switch (type) {
582
0
    case TYPE_TINYINT:
583
0
        return 8;
584
4
    case TYPE_SMALLINT:
585
4
        return 16;
586
187
    case TYPE_INT:
587
187
        return 32;
588
166
    case TYPE_BIGINT:
589
166
        return 64;
590
0
    case TYPE_LARGEINT:
591
0
        return 128;
592
131
    default:
593
131
        return std::nullopt;
594
488
    }
595
488
}
596
597
115
static std::optional<uint8_t> floating_width(PrimitiveType type) {
598
115
    switch (type) {
599
0
    case TYPE_FLOAT:
600
0
        return 32;
601
1
    case TYPE_DOUBLE:
602
1
        return 64;
603
114
    default:
604
114
        return std::nullopt;
605
115
    }
606
115
}
607
608
17
static std::optional<uint8_t> floating_exact_integer_width(PrimitiveType type) {
609
17
    switch (type) {
610
0
    case TYPE_FLOAT:
611
0
        return 24;
612
3
    case TYPE_DOUBLE:
613
3
        return 53;
614
14
    default:
615
14
        return std::nullopt;
616
17
    }
617
17
}
618
619
static bool is_lossless_file_to_table_numeric_cast(const DataTypePtr& file_type,
620
49.2k
                                                   const DataTypePtr& table_type) {
621
49.2k
    const auto file_nested_type = remove_nullable(file_type);
622
49.2k
    const auto table_nested_type = remove_nullable(table_type);
623
49.2k
    if (file_nested_type->equals(*table_nested_type)) {
624
48.9k
        return true;
625
48.9k
    }
626
627
299
    const auto file_primitive_type = file_nested_type->get_primitive_type();
628
299
    const auto table_primitive_type = table_nested_type->get_primitive_type();
629
299
    if (const auto file_width = signed_integer_width(file_primitive_type)) {
630
187
        if (const auto table_width = signed_integer_width(table_primitive_type)) {
631
170
            return *table_width >= *file_width;
632
170
        }
633
17
        if (const auto table_width = floating_exact_integer_width(table_primitive_type)) {
634
3
            return *table_width >= *file_width;
635
3
        }
636
14
        return false;
637
17
    }
638
112
    if (const auto file_width = floating_width(file_primitive_type)) {
639
1
        const auto table_width = floating_width(table_primitive_type);
640
1
        return table_width.has_value() && *table_width >= *file_width;
641
1
    }
642
111
    return false;
643
112
}
644
645
static VExprSPtr rewrite_literal_to_file_type(const VExprSPtr& literal_expr,
646
                                              const FileSlotRewriteInfo& rewrite_info,
647
52.0k
                                              RewriteContext* rewrite_context) {
648
52.0k
    DORIS_CHECK(literal_expr != nullptr);
649
52.0k
    DORIS_CHECK(literal_expr->is_literal());
650
52.0k
    const auto original_literal = original_table_literal(literal_expr, rewrite_context);
651
52.0k
    const Field original_field = literal_field(original_literal);
652
52.0k
    if (rewrite_info.file_type->equals(*original_literal->data_type())) {
653
2.84k
        return original_literal;
654
2.84k
    }
655
    // A literal round trip alone cannot prove that file-local evaluation is safe: the file slot
656
    // itself may lose information when materialized as the table type. For example, DOUBLE 1.5
657
    // becomes BIGINT 1, so table predicate `value = 1` is true while file predicate
658
    // `value = 1.0` is false. Complex Field equality also does not compare nested contents.
659
    // Restrict localization to scalar numeric casts that preserve every file value; unsupported
660
    // and complex casts keep the table predicate and evaluate after materialization.
661
49.2k
    if (!is_lossless_file_to_table_numeric_cast(rewrite_info.file_type,
662
49.2k
                                                original_literal->data_type())) {
663
153
        return nullptr;
664
153
    }
665
49.0k
    Field file_field;
666
49.0k
    try {
667
49.0k
        convert_field_to_type(original_field, *rewrite_info.file_type, &file_field,
668
49.0k
                              original_literal->data_type().get());
669
49.0k
    } catch (const Exception&) {
670
0
        return nullptr;
671
0
    }
672
49.0k
    if (file_field.is_null()) {
673
56
        return nullptr;
674
56
    }
675
49.0k
    if (file_field.get_type() != remove_nullable(rewrite_info.file_type)->get_primitive_type()) {
676
50
        return nullptr;
677
50
    }
678
48.9k
    Field round_trip_field;
679
48.9k
    try {
680
48.9k
        convert_field_to_type(file_field, *original_literal->data_type(), &round_trip_field,
681
48.9k
                              rewrite_info.file_type.get());
682
48.9k
    } catch (const Exception&) {
683
1.18k
        return nullptr;
684
1.18k
    }
685
    // The file-to-table type check protects every possible file value. This round trip separately
686
    // proves that the specific predicate boundary is exactly representable in the file type.
687
47.7k
    if (round_trip_field != original_field) {
688
2
        return nullptr;
689
2
    }
690
47.7k
    auto literal = std::make_shared<SplitLocalFileLiteral>(
691
47.7k
            rewrite_info.file_type, file_field, original_literal->data_type(), original_field);
692
47.7k
    rewrite_context->add_created_expr(literal);
693
47.7k
    return literal;
694
47.7k
}
695
696
static bool rewrite_binary_slot_literal_predicate(
697
        const VExprSPtr& expr,
698
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
699
124k
        RewriteContext* rewrite_context) {
700
124k
    if (!is_binary_comparison_predicate(expr)) {
701
72.0k
        return false;
702
72.0k
    }
703
52.8k
    auto children = expr->children();
704
52.8k
    const VSlotRef* slot_ref = nullptr;
705
52.8k
    const FileSlotRewriteInfo* rewrite_info =
706
52.8k
            find_slot_rewrite_info(children[0], global_to_file_slot, &slot_ref);
707
52.8k
    int slot_child_idx = 0;
708
52.8k
    int literal_child_idx = 1;
709
52.8k
    if (rewrite_info == nullptr) {
710
7.02k
        rewrite_info = find_slot_rewrite_info(children[1], global_to_file_slot, &slot_ref);
711
7.02k
        slot_child_idx = 1;
712
7.02k
        literal_child_idx = 0;
713
7.02k
    }
714
52.8k
    if (rewrite_info == nullptr || slot_ref == nullptr) {
715
7.02k
        return false;
716
7.02k
    }
717
45.8k
    auto literal_expr =
718
45.8k
            unwrap_literal_for_file_cast(children[literal_child_idx], rewrite_info->table_type);
719
45.8k
    if (literal_expr == nullptr) {
720
18
        return false;
721
18
    }
722
723
45.8k
    auto rewritten_literal =
724
45.8k
            rewrite_literal_to_file_type(literal_expr, *rewrite_info, rewrite_context);
725
45.8k
    if (rewritten_literal == nullptr) {
726
1.36k
        children[literal_child_idx] = original_table_literal(literal_expr, rewrite_context);
727
1.36k
        expr->set_children(std::move(children));
728
1.36k
        return false;
729
1.36k
    }
730
731
44.4k
    children[slot_child_idx] = create_file_slot_ref(*slot_ref, *rewrite_info, rewrite_context);
732
44.4k
    children[literal_child_idx] = std::move(rewritten_literal);
733
44.4k
    expr->set_children(std::move(children));
734
44.4k
    return true;
735
45.8k
}
736
737
static bool rewrite_in_slot_literal_predicate(
738
        const VExprSPtr& expr,
739
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
740
80.3k
        RewriteContext* rewrite_context) {
741
80.3k
    if (expr->node_type() != TExprNodeType::IN_PRED || expr->get_num_children() < 2) {
742
78.1k
        return false;
743
78.1k
    }
744
2.21k
    auto children = expr->children();
745
2.21k
    const VSlotRef* slot_ref = nullptr;
746
2.21k
    const FileSlotRewriteInfo* rewrite_info =
747
2.21k
            find_slot_rewrite_info(children[0], global_to_file_slot, &slot_ref);
748
2.21k
    if (rewrite_info == nullptr || slot_ref == nullptr) {
749
76
        return false;
750
76
    }
751
752
2.13k
    VExprSPtrs rewritten_literals;
753
2.13k
    rewritten_literals.reserve(children.size() - 1);
754
7.60k
    for (size_t child_idx = 1; child_idx < children.size(); ++child_idx) {
755
5.51k
        auto literal_expr =
756
5.51k
                unwrap_literal_for_file_cast(children[child_idx], rewrite_info->table_type);
757
5.51k
        if (literal_expr == nullptr) {
758
0
            return false;
759
0
        }
760
5.51k
        auto rewritten_literal =
761
5.51k
                rewrite_literal_to_file_type(literal_expr, *rewrite_info, rewrite_context);
762
5.51k
        if (rewritten_literal == nullptr) {
763
150
            for (size_t restore_idx = 1; restore_idx < children.size(); ++restore_idx) {
764
100
                auto restore_literal = unwrap_literal_for_file_cast(children[restore_idx],
765
100
                                                                    rewrite_info->table_type);
766
100
                if (restore_literal != nullptr) {
767
100
                    children[restore_idx] =
768
100
                            original_table_literal(restore_literal, rewrite_context);
769
100
                }
770
100
            }
771
50
            expr->set_children(std::move(children));
772
50
            return false;
773
50
        }
774
5.46k
        rewritten_literals.push_back(std::move(rewritten_literal));
775
5.46k
    }
776
777
2.08k
    children[0] = create_file_slot_ref(*slot_ref, *rewrite_info, rewrite_context);
778
7.54k
    for (size_t literal_idx = 0; literal_idx < rewritten_literals.size(); ++literal_idx) {
779
5.46k
        children[literal_idx + 1] = std::move(rewritten_literals[literal_idx]);
780
5.46k
    }
781
2.08k
    expr->set_children(std::move(children));
782
2.08k
    return true;
783
2.13k
}
784
785
static VExprSPtr create_file_struct_child_name_literal(const std::string& file_child_name,
786
1.39k
                                                       RewriteContext* rewrite_context) {
787
1.39k
    auto literal = VLiteral::create_shared(std::make_shared<DataTypeString>(),
788
1.39k
                                           Field::create_field<TYPE_STRING>(file_child_name));
789
1.39k
    rewrite_context->add_created_expr(literal);
790
1.39k
    return literal;
791
1.39k
}
792
793
static bool needs_complex_file_slot_cast(const DataTypePtr& file_type,
794
4.49k
                                         const DataTypePtr& table_type) {
795
4.49k
    if (file_type == nullptr || table_type == nullptr || file_type->equals(*table_type)) {
796
0
        return false;
797
0
    }
798
4.49k
    const auto file_nested_type = remove_nullable(file_type);
799
4.49k
    const auto table_nested_type = remove_nullable(table_type);
800
4.49k
    if (file_nested_type->equals(*table_nested_type)) {
801
0
        return false;
802
0
    }
803
4.49k
    return is_complex_type(file_nested_type->get_primitive_type()) ||
804
4.49k
           is_complex_type(table_nested_type->get_primitive_type());
805
4.49k
}
806
807
1.39k
static bool collect_struct_element_chain(const VExprSPtr& expr, std::vector<VExprSPtr>* chain) {
808
1.39k
    DORIS_CHECK(chain != nullptr);
809
1.39k
    if (!is_struct_element_expr(expr)) {
810
0
        return false;
811
0
    }
812
1.39k
    const auto& parent = expr->children()[0];
813
1.39k
    if (is_struct_element_expr(parent)) {
814
157
        if (!collect_struct_element_chain(parent, chain)) {
815
0
            return false;
816
0
        }
817
1.24k
    } else if (!parent->is_slot_ref()) {
818
        // Only support file-local rewrite for struct child chains rooted directly at a top-level
819
        // slot, for example `element_at(s, 'a')` or `element_at(element_at(s, 'a'), 'b')`.
820
        //
821
        // Do not localize computed complex parents such as
822
        // `element_at(element_at(map_values(m), 1), 'full_name')`. The intermediate map/array
823
        // result has already been reshaped by scan projection and may have a different child order
824
        // from the table expression. Partially rewriting that expression against the file block can
825
        // silently evaluate the wrong struct child and filter out valid rows. Those predicates must
826
        // remain as table-level conjuncts and be evaluated after TableReader materialization.
827
0
        return false;
828
0
    }
829
1.39k
    chain->push_back(expr);
830
1.39k
    return true;
831
1.39k
}
832
833
static bool can_filter_before_table_nullability_alignment(const DataTypePtr& file_type,
834
2.64k
                                                          const DataTypePtr& table_type) {
835
2.64k
    DORIS_CHECK(file_type != nullptr);
836
2.64k
    DORIS_CHECK(table_type != nullptr);
837
    // File-local conjuncts run before TableReader validates the materialized table schema. A
838
    // nullable file value mapped to a required table value must therefore reach
839
    // _align_column_nullability(). For example, with file STRUCT<a: Nullable(INT)>, table
840
    // STRUCT<a: BIGINT>, rows [NULL, 20], and `s.a > 10`, filtering in the file domain would drop
841
    // NULL first and hide the table-contract violation. The reverse direction is safe: a required
842
    // file value can always be wrapped as a nullable table value after filtering.
843
2.64k
    return !file_type->is_nullable() || table_type->is_nullable();
844
2.64k
}
845
846
static bool rewrite_struct_element_path_to_file_expr(
847
        const VExprSPtr& expr, const std::vector<ColumnMapping>& mappings,
848
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
849
4.63k
        RewriteContext* rewrite_context) {
850
4.63k
    ResolvedNestedStructPath resolved;
851
4.63k
    if (!resolve_nested_struct_expr_for_file(expr, mappings, &resolved)) {
852
3.39k
        return false;
853
3.39k
    }
854
855
1.24k
    std::vector<VExprSPtr> struct_element_chain;
856
1.24k
    if (!collect_struct_element_chain(expr, &struct_element_chain) ||
857
1.24k
        struct_element_chain.size() != resolved.file_child_names.size() ||
858
1.24k
        struct_element_chain.size() != resolved.file_child_types.size()) {
859
0
        return false;
860
0
    }
861
862
1.24k
    auto root_children = struct_element_chain.front()->children();
863
1.24k
    if (!root_children[0]->is_slot_ref()) {
864
0
        return false;
865
0
    }
866
1.24k
    const auto* slot_ref = assert_cast<const VSlotRef*>(root_children[0].get());
867
1.24k
    const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
868
1.24k
    if (rewrite_it == global_to_file_slot.end()) {
869
0
        return false;
870
0
    }
871
872
    // Check every value-producing level, including the root struct. A nullable parent also makes
873
    // a child access nullable even when the child type itself is required, so checking only the
874
    // final leaf is insufficient. If any file level is more nullable than its table counterpart,
875
    // keep the complete predicate above TableReader so schema validation observes all NULLs before
876
    // row filtering.
877
1.24k
    if (!can_filter_before_table_nullability_alignment(rewrite_it->second.file_type,
878
1.24k
                                                       rewrite_it->second.table_type)) {
879
0
        return false;
880
0
    }
881
2.63k
    for (size_t idx = 0; idx < struct_element_chain.size(); ++idx) {
882
1.39k
        if (!can_filter_before_table_nullability_alignment(
883
1.39k
                    resolved.file_child_types[idx], struct_element_chain[idx]->data_type())) {
884
2
            return false;
885
2
        }
886
1.39k
    }
887
888
    // File-local conjuncts are prepared against the file-reader Block, so both the root slot and
889
    // every struct selector must be expressed in file schema terms. For a renamed Iceberg field,
890
    // keeping the table selector would prepare `element_at(file_struct<rename>, 'renamed')` and
891
    // fail before any rows are read. Rewrite the whole chain while ColumnMapping still preserves
892
    // the table-to-file relationship. Example:
893
    //   table filter: element_at(element_at(s, 'renamed_parent'), 'renamed_leaf')
894
    //   old file:     s<parent<leaf>>
895
    //   file filter:  element_at(element_at(s, 'parent'), 'leaf')
896
1.24k
    root_children[0] = create_file_slot_ref(*slot_ref, rewrite_it->second, rewrite_context);
897
1.24k
    struct_element_chain.front()->set_children(std::move(root_children));
898
2.63k
    for (size_t idx = 0; idx < struct_element_chain.size(); ++idx) {
899
1.39k
        auto children = struct_element_chain[idx]->children();
900
1.39k
        children[1] = create_file_struct_child_name_literal(resolved.file_child_names[idx],
901
1.39k
                                                            rewrite_context);
902
1.39k
        struct_element_chain[idx]->set_children(std::move(children));
903
        // The selector name and the expression return type must be moved to file schema together.
904
        // Example:
905
        //   table filter: element_at(element_at(s, 'new_a'), 'new_aa') = 50
906
        //   old file:     s.new_a STRUCT<aa, bb>
907
        //   file filter:  element_at(element_at(s, 'new_a'), 'aa') = 50
908
        //
909
        // If the inner element_at keeps the table return type STRUCT<new_aa, bb>, preparing the
910
        // outer element_at(..., 'aa') fails before scanning because `aa` is not a table field.
911
1.39k
        struct_element_chain[idx]->data_type() = resolved.file_child_types[idx];
912
1.39k
    }
913
1.24k
    return true;
914
1.24k
}
915
916
static VExprSPtr cast_file_expr_to_table_type(const VExprSPtr& file_expr,
917
                                              const DataTypePtr& table_type,
918
3.94k
                                              RewriteContext* rewrite_context) {
919
3.94k
    DORIS_CHECK(file_expr != nullptr);
920
3.94k
    DORIS_CHECK(table_type != nullptr);
921
3.94k
    DORIS_CHECK(rewrite_context != nullptr);
922
3.94k
    auto cast_expr = Cast::create_shared(table_type);
923
3.94k
    cast_expr->add_child(file_expr);
924
3.94k
    rewrite_context->add_created_expr(cast_expr);
925
3.94k
    return cast_expr;
926
3.94k
}
927
928
// Prefer comparing in the physical file leaf type when a table predicate uses a promoted struct
929
// child. For example, with table STRUCT<a: BIGINT>, old-file STRUCT<a: INT>, and `s.a = 10`, the
930
// localized predicate should be `file_s.a::INT = 10::INT`, not
931
// `CAST(file_s.a::INT AS BIGINT) = 10::BIGINT`. Converting one literal avoids a cast for every row.
932
//
933
// This rewrite is valid only when every possible file value survives file-to-table conversion and
934
// the particular literal survives a table-to-file-to-table round trip. A value such as BIGINT
935
// 2147483648 cannot be represented by an INT file leaf, so that case deliberately falls back to
936
// `CAST(file_s.a AS BIGINT) = 2147483648`, which preserves the original table-level semantics.
937
static bool rewrite_binary_struct_literal_predicate(
938
        const VExprSPtr& expr, const std::vector<ColumnMapping>& filter_mappings,
939
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
940
78.2k
        RewriteContext* rewrite_context, bool* can_localize) {
941
78.2k
    DORIS_CHECK(can_localize != nullptr);
942
78.2k
    if (!is_binary_comparison_predicate(expr)) {
943
69.8k
        return false;
944
69.8k
    }
945
8.39k
    auto children = expr->children();
946
8.39k
    int struct_child_idx = -1;
947
8.39k
    int literal_child_idx = -1;
948
8.39k
    if (is_struct_element_expr(children[0])) {
949
2.18k
        struct_child_idx = 0;
950
2.18k
        literal_child_idx = 1;
951
6.21k
    } else if (is_struct_element_expr(children[1])) {
952
2
        struct_child_idx = 1;
953
2
        literal_child_idx = 0;
954
6.21k
    } else {
955
6.21k
        return false;
956
6.21k
    }
957
958
2.18k
    const auto table_leaf_type = children[struct_child_idx]->data_type();
959
2.18k
    DORIS_CHECK(table_leaf_type != nullptr);
960
2.18k
    auto table_literal = unwrap_literal_for_file_cast(children[literal_child_idx], table_leaf_type);
961
2.18k
    if (table_literal == nullptr ||
962
2.18k
        !rewrite_struct_element_path_to_file_expr(children[struct_child_idx], filter_mappings,
963
2.18k
                                                  global_to_file_slot, rewrite_context)) {
964
1.39k
        return false;
965
1.39k
    }
966
967
789
    const auto file_leaf_type = children[struct_child_idx]->data_type();
968
789
    DORIS_CHECK(file_leaf_type != nullptr);
969
789
    const FileSlotRewriteInfo leaf_rewrite_info {
970
789
            .block_position = 0,
971
789
            .file_type = file_leaf_type,
972
789
            .table_type = table_leaf_type,
973
789
            .file_column_name = {},
974
789
    };
975
789
    auto file_literal =
976
789
            rewrite_literal_to_file_type(table_literal, leaf_rewrite_info, rewrite_context);
977
789
    if (file_literal != nullptr) {
978
755
        children[literal_child_idx] = std::move(file_literal);
979
755
    } else {
980
34
        if (!is_lossless_file_to_table_numeric_cast(file_leaf_type, table_leaf_type)) {
981
            // A narrowing or otherwise lossy cast can fail or produce NULL while TableReader
982
            // materializes the table schema. Evaluating it here could filter the offending row
983
            // before that validation, so keep the complete predicate above TableReader.
984
1
            *can_localize = false;
985
1
            return true;
986
1
        }
987
33
        children[struct_child_idx] = cast_file_expr_to_table_type(children[struct_child_idx],
988
33
                                                                  table_leaf_type, rewrite_context);
989
33
        children[literal_child_idx] = original_table_literal(table_literal, rewrite_context);
990
33
    }
991
788
    expr->set_children(std::move(children));
992
788
    return true;
993
789
}
994
995
// IN must use one comparison type for its probe and every candidate. Rewrite the complete literal
996
// set only when all values are exactly representable in the file leaf type; one unsafe value makes
997
// the whole predicate fall back to a table-type cast. For example, an INT file leaf can evaluate
998
// `BIGINT IN (10, 20)` as `INT IN (10, 20)`, but `BIGINT IN (10, 2147483648)` must stay BIGINT.
999
static bool rewrite_in_struct_literal_predicate(
1000
        const VExprSPtr& expr, const std::vector<ColumnMapping>& filter_mappings,
1001
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
1002
77.4k
        RewriteContext* rewrite_context, bool* can_localize) {
1003
77.4k
    DORIS_CHECK(can_localize != nullptr);
1004
77.4k
    if (expr->node_type() != TExprNodeType::IN_PRED || expr->get_num_children() < 2 ||
1005
77.4k
        !is_struct_element_expr(expr->children()[0])) {
1006
77.4k
        return false;
1007
77.4k
    }
1008
12
    auto children = expr->children();
1009
12
    const auto table_leaf_type = children[0]->data_type();
1010
12
    DORIS_CHECK(table_leaf_type != nullptr);
1011
12
    VExprSPtrs table_literals;
1012
12
    table_literals.reserve(children.size() - 1);
1013
20
    for (size_t child_idx = 1; child_idx < children.size(); ++child_idx) {
1014
8
        auto table_literal = unwrap_literal_for_file_cast(children[child_idx], table_leaf_type);
1015
8
        if (table_literal == nullptr) {
1016
0
            return false;
1017
0
        }
1018
8
        table_literals.push_back(std::move(table_literal));
1019
8
    }
1020
12
    if (!rewrite_struct_element_path_to_file_expr(children[0], filter_mappings, global_to_file_slot,
1021
12
                                                  rewrite_context)) {
1022
0
        return false;
1023
0
    }
1024
1025
12
    const auto file_leaf_type = children[0]->data_type();
1026
12
    DORIS_CHECK(file_leaf_type != nullptr);
1027
12
    const FileSlotRewriteInfo leaf_rewrite_info {
1028
12
            .block_position = 0,
1029
12
            .file_type = file_leaf_type,
1030
12
            .table_type = table_leaf_type,
1031
12
            .file_column_name = {},
1032
12
    };
1033
12
    VExprSPtrs file_literals;
1034
12
    file_literals.reserve(table_literals.size());
1035
12
    for (const auto& table_literal : table_literals) {
1036
8
        auto file_literal =
1037
8
                rewrite_literal_to_file_type(table_literal, leaf_rewrite_info, rewrite_context);
1038
8
        if (file_literal == nullptr) {
1039
1
            if (!is_lossless_file_to_table_numeric_cast(file_leaf_type, table_leaf_type)) {
1040
0
                *can_localize = false;
1041
0
                return true;
1042
0
            }
1043
1
            children[0] =
1044
1
                    cast_file_expr_to_table_type(children[0], table_leaf_type, rewrite_context);
1045
3
            for (size_t literal_idx = 0; literal_idx < table_literals.size(); ++literal_idx) {
1046
2
                children[literal_idx + 1] =
1047
2
                        original_table_literal(table_literals[literal_idx], rewrite_context);
1048
2
            }
1049
1
            expr->set_children(std::move(children));
1050
1
            return true;
1051
1
        }
1052
7
        file_literals.push_back(std::move(file_literal));
1053
7
    }
1054
1055
17
    for (size_t literal_idx = 0; literal_idx < file_literals.size(); ++literal_idx) {
1056
6
        children[literal_idx + 1] = std::move(file_literals[literal_idx]);
1057
6
    }
1058
11
    expr->set_children(std::move(children));
1059
11
    return true;
1060
12
}
1061
1062
static VExprSPtr rewrite_struct_or_slot_expr_to_file_expr(
1063
        const VExprSPtr& expr,
1064
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
1065
        const std::vector<ColumnMapping>& filter_mappings, RewriteContext* rewrite_context,
1066
28.6k
        bool* can_localize) {
1067
28.6k
    if (is_struct_element_expr(expr)) {
1068
2.45k
        const auto table_leaf_type = expr->data_type();
1069
2.45k
        if (!rewrite_struct_element_path_to_file_expr(expr, filter_mappings, global_to_file_slot,
1070
2.45k
                                                      rewrite_context)) {
1071
            // The scanner still evaluates the original table-level conjunct after TableReader
1072
            // finalizes the output block. Skipping an unlocalizable file conjunct is therefore
1073
            // safer than preparing a partially rewritten expression against the wrong struct
1074
            // layout. In particular, do not generate file-local conjuncts for computed complex
1075
            // parents such as `element_at(element_at(map_values(m), 1), 'field')`; only direct
1076
            // slot-rooted struct chains are supported here.
1077
2.00k
            *can_localize = false;
1078
2.00k
            return expr;
1079
2.00k
        }
1080
447
        DORIS_CHECK(table_leaf_type != nullptr);
1081
447
        DORIS_CHECK(expr->data_type() != nullptr);
1082
447
        if (!expr->data_type()->equals(*table_leaf_type)) {
1083
0
            if (!is_lossless_file_to_table_numeric_cast(expr->data_type(), table_leaf_type)) {
1084
0
                *can_localize = false;
1085
0
                return expr;
1086
0
            }
1087
            // Path localization changes the leaf to the physical file type. For example, after an
1088
            // Iceberg evolution from STRUCT<a: INT> to STRUCT<a: BIGINT>, the localized old-file
1089
            // predicate is initially `element_at(file_col, 'a')::INT = 10::BIGINT`. Cast only the
1090
            // leaf back to BIGINT so the comparison has matching operands without forcing a cast
1091
            // of the entire evolved struct (whose children may also have been added or reordered).
1092
0
            return cast_file_expr_to_table_type(expr, table_leaf_type, rewrite_context);
1093
0
        }
1094
447
        return expr;
1095
447
    }
1096
1097
26.2k
    DORIS_CHECK(expr->is_slot_ref());
1098
26.2k
    const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
1099
26.2k
    const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
1100
26.2k
    if (rewrite_it == global_to_file_slot.end()) {
1101
0
        return expr;
1102
0
    }
1103
26.2k
    const auto& rewrite_info = rewrite_it->second;
1104
26.2k
    auto file_slot = create_file_slot_ref(*slot_ref, rewrite_info, rewrite_context);
1105
26.2k
    if (rewrite_info.file_type->equals(*rewrite_info.table_type)) {
1106
21.7k
        return file_slot;
1107
21.7k
    }
1108
4.48k
    if (needs_complex_file_slot_cast(rewrite_info.file_type, rewrite_info.table_type)) {
1109
        // Generic file-local expressions cannot safely cast an evolved complex file slot back to
1110
        // the table type. For example, ARRAY_CONTAINS(MAP_KEYS(m), 'person5') only reads map keys,
1111
        // but CAST(file_m AS table_m) first forces an incompatible old value struct into the new
1112
        // layout. Keep such predicates at table level, after TableReader materializes evolution.
1113
590
        *can_localize = false;
1114
590
        return expr;
1115
590
    }
1116
3.89k
    return cast_file_expr_to_table_type(file_slot, rewrite_info.table_type, rewrite_context);
1117
4.48k
}
1118
1119
static VExprSPtr rewrite_table_expr_to_file_expr(
1120
        const VExprSPtr& expr,
1121
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
1122
        const std::vector<ColumnMapping>& filter_mappings, RewriteContext* rewrite_context,
1123
129k
        bool* can_localize) {
1124
129k
    if (expr == nullptr) {
1125
0
        return nullptr;
1126
0
    }
1127
129k
    DORIS_CHECK(rewrite_context != nullptr);
1128
129k
    DORIS_CHECK(can_localize != nullptr);
1129
129k
    if (auto* runtime_filter = dynamic_cast<RuntimeFilterExpr*>(expr.get());
1130
129k
        runtime_filter != nullptr) {
1131
4.25k
        auto impl = runtime_filter->get_impl();
1132
4.25k
        if (impl == nullptr) {
1133
0
            *can_localize = false;
1134
0
            return expr;
1135
0
        }
1136
4.25k
        auto localized_impl = rewrite_table_expr_to_file_expr(
1137
4.25k
                impl, global_to_file_slot, filter_mappings, rewrite_context, can_localize);
1138
4.25k
        if (!*can_localize) {
1139
0
            return expr;
1140
0
        }
1141
4.25k
        runtime_filter->set_impl(std::move(localized_impl));
1142
4.25k
        return expr;
1143
4.25k
    }
1144
124k
    if (rewrite_binary_slot_literal_predicate(expr, global_to_file_slot, rewrite_context)) {
1145
44.3k
        return expr;
1146
44.3k
    }
1147
80.5k
    if (rewrite_in_slot_literal_predicate(expr, global_to_file_slot, rewrite_context)) {
1148
2.04k
        return expr;
1149
2.04k
    }
1150
78.5k
    if (rewrite_binary_struct_literal_predicate(expr, filter_mappings, global_to_file_slot,
1151
78.5k
                                                rewrite_context, can_localize)) {
1152
789
        return expr;
1153
789
    }
1154
77.7k
    if (rewrite_in_struct_literal_predicate(expr, filter_mappings, global_to_file_slot,
1155
77.7k
                                            rewrite_context, can_localize)) {
1156
4
        return expr;
1157
4
    }
1158
77.7k
    if (is_struct_element_expr(expr) || expr->is_slot_ref()) {
1159
28.6k
        return rewrite_struct_or_slot_expr_to_file_expr(expr, global_to_file_slot, filter_mappings,
1160
28.6k
                                                        rewrite_context, can_localize);
1161
28.6k
    }
1162
    // The input is a split-local cloned tree. A previous split-local clone may already have
1163
    // inserted Cast(slot). Keep that rewrite idempotent: rewrite the cast child from table slot to
1164
    // the current split's file slot, and drop the cast when the current split no longer needs it.
1165
49.0k
    if (is_cast_expr(expr) && expr->get_num_children() == 1) {
1166
1.66k
        const auto& child = expr->children()[0];
1167
1.66k
        if (child->is_slot_ref()) {
1168
1.60k
            const auto* slot_ref = assert_cast<const VSlotRef*>(child.get());
1169
1.60k
            const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
1170
1.60k
            if (rewrite_it != global_to_file_slot.end() &&
1171
1.60k
                expr->data_type()->equals(*rewrite_it->second.table_type)) {
1172
1
                auto rewritten_child =
1173
1
                        create_file_slot_ref(*slot_ref, rewrite_it->second, rewrite_context);
1174
1
                if (rewrite_it->second.file_type->equals(*rewrite_it->second.table_type)) {
1175
0
                    return rewritten_child;
1176
0
                }
1177
1
                if (needs_complex_file_slot_cast(rewrite_it->second.file_type,
1178
1
                                                 rewrite_it->second.table_type)) {
1179
0
                    *can_localize = false;
1180
0
                    return expr;
1181
0
                }
1182
1
                expr->set_children({std::move(rewritten_child)});
1183
1
                return expr;
1184
1
            }
1185
1.60k
        }
1186
1.66k
    }
1187
1188
49.0k
    VExprSPtrs rewritten_children;
1189
49.0k
    rewritten_children.reserve(expr->children().size());
1190
49.9k
    for (const auto& child : expr->children()) {
1191
49.9k
        rewritten_children.push_back(rewrite_table_expr_to_file_expr(
1192
49.9k
                child, global_to_file_slot, filter_mappings, rewrite_context, can_localize));
1193
49.9k
    }
1194
49.0k
    expr->set_children(std::move(rewritten_children));
1195
49.0k
    return expr;
1196
49.0k
}
1197
1198
static constexpr const char* ROW_LINEAGE_ROW_ID = "_row_id";
1199
static constexpr const char* ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER = "_last_updated_sequence_number";
1200
static constexpr int32_t ROW_LINEAGE_ROW_ID_FIELD_ID = 2147483540;
1201
static constexpr int32_t ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER_FIELD_ID = 2147483539;
1202
1203
17
static TableVirtualColumnType row_lineage_virtual_column_type(const std::string& column_name) {
1204
17
    if (column_name == ROW_LINEAGE_ROW_ID) {
1205
2
        return TableVirtualColumnType::ROW_ID;
1206
2
    }
1207
15
    if (column_name == ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER) {
1208
2
        return TableVirtualColumnType::LAST_UPDATED_SEQUENCE_NUMBER;
1209
2
    }
1210
13
    return TableVirtualColumnType::INVALID;
1211
15
}
1212
1213
static TableVirtualColumnType row_lineage_virtual_column_type_by_field_id(
1214
110k
        const ColumnDefinition& column) {
1215
110k
    if (!column.has_identifier_field_id()) {
1216
1.08k
        return TableVirtualColumnType::INVALID;
1217
1.08k
    }
1218
109k
    switch (column.get_identifier_field_id()) {
1219
2.08k
    case ROW_LINEAGE_ROW_ID_FIELD_ID:
1220
2.08k
        return TableVirtualColumnType::ROW_ID;
1221
1.75k
    case ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER_FIELD_ID:
1222
1.75k
        return TableVirtualColumnType::LAST_UPDATED_SEQUENCE_NUMBER;
1223
105k
    default:
1224
105k
        return TableVirtualColumnType::INVALID;
1225
109k
    }
1226
109k
}
1227
1228
static TableVirtualColumnType row_lineage_virtual_column_type(const ColumnDefinition& column,
1229
111k
                                                              TableColumnMappingMode mode) {
1230
111k
    switch (mode) {
1231
111k
    case TableColumnMappingMode::BY_FIELD_ID:
1232
111k
        return row_lineage_virtual_column_type_by_field_id(column);
1233
17
    case TableColumnMappingMode::BY_NAME:
1234
17
    case TableColumnMappingMode::BY_INDEX:
1235
17
        return row_lineage_virtual_column_type(column.name);
1236
111k
    }
1237
0
    return TableVirtualColumnType::INVALID;
1238
111k
}
1239
1240
// Returns true when the current file type is not the exact nested type the scan should expose.
1241
// This is about building the projected file-side type/projection, not about whether TableReader
1242
// later needs to rematerialize the complex value back to table layout.
1243
547k
static bool needs_projected_file_type_rebuild(const ColumnMapping& mapping) {
1244
547k
    if (!is_complex_type(mapping.file_type->get_primitive_type())) {
1245
309k
        return false;
1246
309k
    }
1247
238k
    if (mapping.child_mappings.empty()) {
1248
0
        return false;
1249
0
    }
1250
238k
    DORIS_CHECK(mapping.file_type != nullptr);
1251
238k
    DORIS_CHECK(mapping.table_type != nullptr);
1252
238k
    if (remove_nullable(mapping.file_type)->get_primitive_type() !=
1253
238k
        remove_nullable(mapping.table_type)->get_primitive_type()) {
1254
0
        return true;
1255
0
    }
1256
238k
    if (!mapping.table_type->equals(*mapping.file_type)) {
1257
19.3k
        return true;
1258
19.3k
    }
1259
340k
    for (const auto& child_mapping : mapping.child_mappings) {
1260
        // Rename-only child mappings do not change the file-side projected shape. If field-id
1261
        // matching maps table child `renamed_b` to file child `b`, the file reader can still expose
1262
        // the original file type as long as child count/order/types are unchanged.
1263
340k
        if (!child_mapping.file_local_id.has_value() ||
1264
340k
            needs_projected_file_type_rebuild(child_mapping)) {
1265
689
            return true;
1266
689
        }
1267
340k
    }
1268
218k
    return false;
1269
218k
}
1270
1271
static std::optional<size_t> file_child_ordinal_in_scan_type(const ColumnMapping& mapping,
1272
307k
                                                             const ColumnMapping& child_mapping) {
1273
307k
    if (!child_mapping.file_local_id.has_value()) {
1274
279
        return std::nullopt;
1275
279
    }
1276
306k
    const auto& file_children = !mapping.projected_file_children.empty()
1277
307k
                                        ? mapping.projected_file_children
1278
18.4E
                                        : mapping.original_file_children;
1279
433k
    const auto child_it = std::ranges::find_if(file_children, [&](const ColumnDefinition& child) {
1280
433k
        return child.file_local_id() == *child_mapping.file_local_id;
1281
433k
    });
1282
306k
    if (child_it == file_children.end()) {
1283
0
        return std::nullopt;
1284
0
    }
1285
306k
    return static_cast<size_t>(std::distance(file_children.begin(), child_it));
1286
306k
}
1287
1288
1.28M
static bool needs_complex_rematerialize(const ColumnMapping& mapping) {
1289
1.28M
    if (mapping.child_mappings.empty()) {
1290
1.07M
        return false;
1291
1.07M
    }
1292
212k
    if (mapping.table_type == nullptr || mapping.file_type == nullptr ||
1293
212k
        !mapping.table_type->equals(*mapping.file_type)) {
1294
11.8k
        return true;
1295
11.8k
    }
1296
505k
    for (size_t table_child_idx = 0; table_child_idx < mapping.child_mappings.size();
1297
307k
         ++table_child_idx) {
1298
307k
        const auto& child_mapping = mapping.child_mappings[table_child_idx];
1299
307k
        const auto file_child_idx = file_child_ordinal_in_scan_type(mapping, child_mapping);
1300
307k
        if (!file_child_idx.has_value() || *file_child_idx != table_child_idx ||
1301
307k
            needs_complex_rematerialize(child_mapping) ||
1302
307k
            (child_mapping.table_type != nullptr && child_mapping.file_type != nullptr &&
1303
305k
             !child_mapping.table_type->equals(*child_mapping.file_type))) {
1304
2.24k
            return true;
1305
2.24k
        }
1306
307k
    }
1307
197k
    return false;
1308
199k
}
1309
1310
1.02M
static bool mapping_can_use_file_column_directly(const ColumnMapping& mapping) {
1311
1.02M
    if (mapping.table_type == nullptr || mapping.file_type == nullptr) {
1312
0
        return false;
1313
0
    }
1314
1.02M
    const auto table_type = remove_nullable(mapping.table_type);
1315
1.02M
    const auto file_type = remove_nullable(mapping.file_type);
1316
1.02M
    const bool same_timestamptz_with_different_scale =
1317
1.02M
            table_type->get_primitive_type() == TYPE_TIMESTAMPTZ &&
1318
1.02M
            file_type->get_primitive_type() == TYPE_TIMESTAMPTZ;
1319
1.02M
    if (!mapping.table_type->equals(*mapping.file_type) && !same_timestamptz_with_different_scale) {
1320
69.9k
        return false;
1321
69.9k
    }
1322
957k
    return !needs_complex_rematerialize(mapping);
1323
1.02M
}
1324
1325
1.27M
static bool type_contains_varbinary(const DataTypePtr& type) {
1326
1.27M
    DORIS_CHECK(type != nullptr);
1327
1.27M
    const auto nested_type = remove_nullable(type);
1328
1.27M
    switch (nested_type->get_primitive_type()) {
1329
1.87k
    case TYPE_VARBINARY:
1330
1.87k
        return true;
1331
104k
    case TYPE_ARRAY:
1332
104k
        return type_contains_varbinary(
1333
104k
                assert_cast<const DataTypeArray&>(*nested_type).get_nested_type());
1334
81.8k
    case TYPE_MAP: {
1335
81.8k
        const auto& map_type = assert_cast<const DataTypeMap&>(*nested_type);
1336
81.8k
        return type_contains_varbinary(map_type.get_key_type()) ||
1337
81.8k
               type_contains_varbinary(map_type.get_value_type());
1338
0
    }
1339
83.5k
    case TYPE_STRUCT:
1340
83.5k
        return std::ranges::any_of(
1341
83.5k
                assert_cast<const DataTypeStruct&>(*nested_type).get_elements(),
1342
164k
                [](const DataTypePtr& child_type) { return type_contains_varbinary(child_type); });
1343
1.01M
    default:
1344
1.01M
        return false;
1345
1.27M
    }
1346
1.27M
}
1347
1348
849k
static FilterConversionType direct_filter_conversion(const ColumnMapping& mapping) {
1349
849k
    DORIS_CHECK(mapping.table_type != nullptr);
1350
849k
    DORIS_CHECK(mapping.file_type != nullptr);
1351
    // FileScanOperator deliberately keeps VARBINARY predicates above external readers. Their
1352
    // physical binary representations are not uniformly supported by reader-side expression and
1353
    // metadata filtering, so localizing a late runtime filter here can incorrectly reject rows.
1354
    // Apply the same rule to a complex root because generic array/map/struct expressions rewrite
1355
    // the root slot and can otherwise expose a nested VARBINARY child to the reader.
1356
849k
    if (type_contains_varbinary(mapping.table_type)) {
1357
1.86k
        return FilterConversionType::FINALIZE_ONLY;
1358
1.86k
    }
1359
847k
    const auto table_type = remove_nullable(mapping.table_type);
1360
847k
    const auto file_type = remove_nullable(mapping.file_type);
1361
    // TIMESTAMPTZ scale mismatch is intentionally materialized as pass-through: a SQL cast rounds
1362
    // fractional seconds. A file-local cast would therefore filter different instants from the
1363
    // scanner-level predicate evaluated on the pass-through value.
1364
847k
    if (table_type->get_primitive_type() == TYPE_TIMESTAMPTZ &&
1365
847k
        file_type->get_primitive_type() == TYPE_TIMESTAMPTZ &&
1366
847k
        !mapping.table_type->equals(*mapping.file_type)) {
1367
1
        return FilterConversionType::FINALIZE_ONLY;
1368
1
    }
1369
847k
    return mapping.is_trivial ? FilterConversionType::COPY_DIRECTLY
1370
847k
                              : FilterConversionType::CAST_FILTER;
1371
847k
}
1372
1373
19.6k
static FilterConversionType projected_filter_conversion(const ColumnMapping& mapping) {
1374
19.6k
    const auto conversion = direct_filter_conversion(mapping);
1375
19.6k
    return !mapping.is_trivial && conversion != FilterConversionType::FINALIZE_ONLY
1376
19.6k
                   ? FilterConversionType::READER_EXPRESSION
1377
19.6k
                   : conversion;
1378
19.6k
}
1379
1380
static const ColumnDefinition* find_file_child_for_mapping(const ColumnDefinition& table_child,
1381
                                                           const ColumnDefinition& file_parent,
1382
                                                           TableColumnMappingMode mode,
1383
                                                           size_t table_child_idx,
1384
329k
                                                           bool allow_ordinal_fallback) {
1385
329k
    const auto file_parent_type = remove_nullable(file_parent.type)->get_primitive_type();
1386
329k
    switch (file_parent_type) {
1387
87.9k
    case TYPE_ARRAY:
1388
87.9k
        DORIS_CHECK(file_parent.children.size() == 1);
1389
87.9k
        return &file_parent.children[0];
1390
148k
    case TYPE_MAP:
1391
148k
        DORIS_CHECK(file_parent.children.size() == 2);
1392
148k
        if (table_child.name == "key") {
1393
74.0k
            return &file_parent.children[0];
1394
74.0k
        }
1395
74.1k
        if (table_child.name == "value") {
1396
74.1k
            return &file_parent.children[1];
1397
74.1k
        }
1398
40
        if (table_child.local_id == 0 || table_child.local_id == 1) {
1399
0
            return &file_parent.children[table_child.local_id];
1400
0
        }
1401
40
        return nullptr;
1402
93.5k
    default:
1403
        // Hive BY_INDEX is a top-level column matching rule. Once a complex root is selected by
1404
        // file position, nested struct children follow Hive reader's historical name matching
1405
        // semantics; their integer identifiers can be field ids, not file positions.
1406
93.5k
        const auto nested_mode =
1407
93.5k
                mode == TableColumnMappingMode::BY_INDEX ? TableColumnMappingMode::BY_NAME : mode;
1408
93.5k
        if (const auto* file_child =
1409
93.5k
                    matcher_for_mode(nested_mode).find(table_child, file_parent.children);
1410
93.5k
            file_child != nullptr) {
1411
87.8k
            return file_child;
1412
87.8k
        }
1413
5.69k
        if (allow_ordinal_fallback && mode == TableColumnMappingMode::BY_FIELD_ID &&
1414
5.69k
            !table_child.has_identifier_field_id()) {
1415
            // Synthetic children are derived from the table DataType when nested ColumnDefinition
1416
            // metadata has been pruned away. They do not carry Iceberg field ids, so try a name
1417
            // match before falling back to ordinal order. Example:
1418
            //   table value type: Struct(age, full_name, gender)
1419
            //   old file value:   Struct(name, age)
1420
            // Name matching keeps `age -> age`; the later unused-child fallback can then map the
1421
            // renamed `full_name -> name` instead of consuming `age` twice.
1422
3
            if (const auto* file_child = NameMatcher().find(table_child, file_parent.children);
1423
3
                file_child != nullptr) {
1424
1
                return file_child;
1425
1
            }
1426
3
        }
1427
        // Some callers only carry the full complex DataType for a projected table column, without
1428
        // expanded nested ColumnDefinitions. In that case we can still preserve full materialization
1429
        // by walking table/file struct fields by ordinal. This is a fallback only: explicit
1430
        // ColumnDefinition children keep using the requested table-format matching rule, which is
1431
        // required for precise schema evolution.
1432
5.69k
        if (allow_ordinal_fallback && table_child_idx < file_parent.children.size()) {
1433
3
            return &file_parent.children[table_child_idx];
1434
3
        }
1435
5.68k
        return nullptr;
1436
329k
    }
1437
329k
}
1438
1439
static ColumnDefinition synthetic_child_definition(const std::string& name, DataTypePtr type,
1440
93.3k
                                                   int32_t local_id) {
1441
93.3k
    ColumnDefinition child;
1442
93.3k
    child.identifier = Field::create_field<TYPE_STRING>(name);
1443
93.3k
    child.local_id = local_id;
1444
93.3k
    child.name = name;
1445
93.3k
    child.type = std::move(type);
1446
93.3k
    return child;
1447
93.3k
}
1448
1449
static std::vector<ColumnDefinition> synthesize_complex_children_from_type(
1450
46.6k
        const DataTypePtr& type) {
1451
46.6k
    std::vector<ColumnDefinition> children;
1452
46.6k
    if (type == nullptr) {
1453
0
        return children;
1454
0
    }
1455
46.6k
    const auto nested_type = remove_nullable(type);
1456
46.6k
    switch (nested_type->get_primitive_type()) {
1457
0
    case TYPE_ARRAY: {
1458
0
        const auto* array_type = assert_cast<const DataTypeArray*>(nested_type.get());
1459
0
        children.push_back(synthetic_child_definition("element", array_type->get_nested_type(), 0));
1460
0
        break;
1461
0
    }
1462
1
    case TYPE_MAP: {
1463
1
        const auto* map_type = assert_cast<const DataTypeMap*>(nested_type.get());
1464
1
        children.push_back(synthetic_child_definition("key", map_type->get_key_type(), 0));
1465
1
        children.push_back(synthetic_child_definition("value", map_type->get_value_type(), 1));
1466
1
        break;
1467
0
    }
1468
46.6k
    case TYPE_STRUCT: {
1469
46.6k
        const auto* struct_type = assert_cast<const DataTypeStruct*>(nested_type.get());
1470
46.6k
        children.reserve(struct_type->get_elements().size());
1471
140k
        for (size_t idx = 0; idx < struct_type->get_elements().size(); ++idx) {
1472
93.5k
            children.push_back(synthetic_child_definition(struct_type->get_element_name(idx),
1473
93.5k
                                                          struct_type->get_element(idx),
1474
93.5k
                                                          cast_set<int32_t>(idx)));
1475
93.5k
        }
1476
46.6k
        break;
1477
0
    }
1478
0
    default:
1479
0
        break;
1480
46.6k
    }
1481
46.6k
    return children;
1482
46.6k
}
1483
1484
static void align_struct_child_types_with_parent(const DataTypePtr& parent_type,
1485
46.6k
                                                 std::vector<ColumnDefinition>& children) {
1486
46.6k
    const auto nested_parent_type = remove_nullable(parent_type);
1487
46.6k
    DORIS_CHECK(nested_parent_type->get_primitive_type() == TYPE_STRUCT);
1488
46.6k
    const auto type_children = synthesize_complex_children_from_type(parent_type);
1489
93.5k
    for (auto& child : children) {
1490
93.5k
        const auto type_child = std::ranges::find_if(
1491
175k
                type_children, [&](const auto& candidate) { return candidate.name == child.name; });
1492
93.5k
        DORIS_CHECK(type_child != type_children.end())
1493
4
                << "Complex child '" << child.name
1494
4
                << "' is absent from its parent table type: " << parent_type->get_name();
1495
        // The parent DataType is the authoritative output contract. Nested schema descriptors can
1496
        // omit child nullability even though the parent struct still declares Nullable(String).
1497
        // For example, the Iceberg full-schema-change case maps nullable `location` to `city`, but
1498
        // its child descriptor carries String. Keeping String here makes rematerialization strip
1499
        // the child's null map and creates Struct(String) under a Struct(Nullable(String)) type.
1500
93.5k
        child.type = type_child->type;
1501
93.5k
    }
1502
46.6k
}
1503
1504
static bool has_table_child_named(const std::vector<ColumnDefinition>& children,
1505
10.5k
                                  std::string_view name) {
1506
15.8k
    return std::ranges::any_of(children, [&](const ColumnDefinition& child) {
1507
15.8k
        return std::string_view(child.name) == name;
1508
15.8k
    });
1509
10.5k
}
1510
1511
static void complete_required_complex_children_from_type(const DataTypePtr& type,
1512
19.1k
                                                         std::vector<ColumnDefinition>& children) {
1513
19.1k
    if (type == nullptr) {
1514
0
        return;
1515
0
    }
1516
19.1k
    const auto nested_type = remove_nullable(type);
1517
19.1k
    switch (nested_type->get_primitive_type()) {
1518
5.27k
    case TYPE_MAP: {
1519
5.27k
        const auto* map_type = assert_cast<const DataTypeMap*>(nested_type.get());
1520
        // MAP key/value are structural children, not independently materializable table fields.
1521
        // A key-only projection can still be attached to a whole-map output root, for example:
1522
        //   SELECT * FROM t WHERE ARRAY_CONTAINS(MAP_KEYS(new_map_column), 'person5')
1523
        //
1524
        // In that shape the scanner keeps the value stream readable, but the table projection can
1525
        // carry only the key child. Add the missing value child so recursive mapping can evolve the
1526
        // value type instead of letting TableReader cast old/new value structs directly.
1527
5.27k
        if (has_table_child_named(children, "key") && !has_table_child_named(children, "value")) {
1528
2
            children.push_back(synthetic_child_definition("value", map_type->get_value_type(), 1));
1529
2
        }
1530
5.27k
        break;
1531
0
    }
1532
5.29k
    case TYPE_ARRAY:
1533
        // ARRAY has only one required structural child (`element`), so a non-empty projection is
1534
        // already rooted at the element path.
1535
5.29k
        break;
1536
8.58k
    case TYPE_STRUCT:
1537
        // STRUCT children are real fields and must remain prunable. Completing missing struct
1538
        // fields here would turn `SELECT s.a` into a full-struct read and undo nested projection.
1539
8.58k
        break;
1540
0
    default:
1541
0
        break;
1542
19.1k
    }
1543
19.1k
}
1544
1545
struct PreparedTableChildren {
1546
    std::vector<ColumnDefinition> children;
1547
    bool synthesized_from_type = false;
1548
};
1549
1550
static PreparedTableChildren prepare_table_children_for_mapping(
1551
831k
        const ColumnDefinition& table_column, const DataTypePtr& file_type) {
1552
831k
    PreparedTableChildren prepared {.children = table_column.children};
1553
831k
    const auto nested_table_type = remove_nullable(table_column.type);
1554
1555
    // Some scan paths, especially SELECT *, only carry the complete complex DataType for a table
1556
    // column and leave ColumnDefinition::children empty. Synthesize the hierarchy so recursive
1557
    // mapping can evolve nested fields instead of falling back to an invalid whole-column cast.
1558
831k
    prepared.synthesized_from_type = prepared.children.empty() &&
1559
831k
                                     is_complex_type(nested_table_type->get_primitive_type()) &&
1560
831k
                                     !table_column.type->equals(*file_type);
1561
831k
    if (prepared.synthesized_from_type) {
1562
4
        prepared.children = synthesize_complex_children_from_type(table_column.type);
1563
831k
    } else if (!prepared.children.empty() && !table_column.type->equals(*file_type)) {
1564
19.1k
        complete_required_complex_children_from_type(table_column.type, prepared.children);
1565
19.1k
    }
1566
1567
831k
    if (!prepared.children.empty() && nested_table_type->get_primitive_type() == TYPE_STRUCT) {
1568
        // Struct children are table fields, so the parent Struct type is authoritative for their
1569
        // nullability. ARRAY and MAP children are format-level structural wrappers and keep the
1570
        // descriptor types used by their recursive mappings.
1571
46.6k
        align_struct_child_types_with_parent(table_column.type, prepared.children);
1572
46.6k
    }
1573
831k
    return prepared;
1574
831k
}
1575
1576
208k
static Status validate_file_schema_children(const ColumnDefinition& file_field) {
1577
208k
    if (file_field.type == nullptr) {
1578
0
        return Status::InternalError("File column '{}' has null type", file_field.name);
1579
0
    }
1580
208k
    const auto nested_type = remove_nullable(file_field.type);
1581
208k
    size_t expected_children = 0;
1582
208k
    bool complex_with_fixed_children = true;
1583
208k
    switch (nested_type->get_primitive_type()) {
1584
87.9k
    case TYPE_ARRAY:
1585
87.9k
        expected_children = 1;
1586
87.9k
        break;
1587
74.1k
    case TYPE_MAP:
1588
74.1k
        expected_children = 2;
1589
74.1k
        break;
1590
46.6k
    case TYPE_STRUCT:
1591
46.6k
        expected_children =
1592
46.6k
                assert_cast<const DataTypeStruct*>(nested_type.get())->get_elements().size();
1593
46.6k
        break;
1594
0
    default:
1595
0
        complex_with_fixed_children = false;
1596
0
        break;
1597
208k
    }
1598
208k
    if (!complex_with_fixed_children || file_field.children.size() == expected_children) {
1599
208k
        return Status::OK();
1600
208k
    }
1601
18.4E
    return Status::InternalError(
1602
18.4E
            "Malformed complex file schema for column '{}': type={}, expected_children={}, "
1603
18.4E
            "actual_children={}",
1604
18.4E
            file_field.name, file_field.type->get_name(), expected_children,
1605
18.4E
            file_field.children.size());
1606
208k
}
1607
1608
452k
static bool has_projected_file_children(const ColumnMapping& mapping) {
1609
452k
    if (mapping.original_file_children.empty() || mapping.projected_file_children.empty()) {
1610
371k
        return false;
1611
371k
    }
1612
80.8k
    if (mapping.original_file_children.size() != mapping.projected_file_children.size()) {
1613
5.87k
        return true;
1614
5.87k
    }
1615
201k
    for (size_t idx = 0; idx < mapping.original_file_children.size(); ++idx) {
1616
126k
        if (mapping.original_file_children[idx].file_local_id() !=
1617
126k
            mapping.projected_file_children[idx].file_local_id()) {
1618
0
            return true;
1619
0
        }
1620
126k
    }
1621
74.9k
    return false;
1622
74.9k
}
1623
1624
452k
static bool needs_nested_file_projection(const ColumnMapping& mapping) {
1625
452k
    if (has_projected_file_children(mapping)) {
1626
        // Return True if the projected child column is missing / re-ordered
1627
5.87k
        return true;
1628
5.87k
    }
1629
446k
    return std::ranges::any_of(mapping.child_mappings, [](const ColumnMapping& child_mapping) {
1630
128k
        return needs_nested_file_projection(child_mapping);
1631
128k
    });
1632
452k
}
1633
1634
static Status build_complex_projection(const ColumnMapping& mapping, LocalColumnIndex* projection);
1635
1636
// Build the projected file children/type according to the pruned complex projection. For example,
1637
// if we have a struct column `s` with children `id` and `name`, and the projection only keeps
1638
// `s.name`, then the file reader should expose `STRUCT<name ...>`.
1639
static Status rebuild_projected_file_children_and_type(
1640
        const DataTypePtr& file_type, const std::vector<ColumnDefinition>& original_file_children,
1641
        const std::vector<ColumnMapping>& child_mappings,
1642
19.7k
        std::vector<ColumnDefinition>* projected_file_children, DataTypePtr* projected_type) {
1643
19.7k
    DORIS_CHECK(file_type != nullptr);
1644
19.7k
    DORIS_CHECK(projected_file_children != nullptr);
1645
19.7k
    DORIS_CHECK(projected_type != nullptr);
1646
19.7k
    ColumnDefinition field;
1647
19.7k
    field.type = file_type;
1648
19.7k
    field.children = original_file_children;
1649
19.7k
    LocalColumnIndex projection = LocalColumnIndex::partial_local(-1);
1650
19.7k
    projection.children.reserve(child_mappings.size());
1651
30.3k
    for (const auto* child_mapping : present_child_mappings_in_file_order(child_mappings)) {
1652
30.3k
        DORIS_CHECK(child_mapping->file_local_id.has_value());
1653
30.3k
        LocalColumnIndex child_projection;
1654
30.3k
        RETURN_IF_ERROR(build_complex_projection(*child_mapping, &child_projection));
1655
30.3k
        projection.children.push_back(std::move(child_projection));
1656
30.3k
    }
1657
1658
19.7k
    ColumnDefinition projected_field;
1659
19.7k
    RETURN_IF_ERROR(project_column_definition(field, projection, &projected_field));
1660
19.7k
    *projected_file_children = std::move(projected_field.children);
1661
19.7k
    *projected_type = std::move(projected_field.type);
1662
19.7k
    return Status::OK();
1663
19.7k
}
1664
1665
// Build the complex column projection according to the ColumnMapping which is re-ordered by the
1666
// file-schema's order.
1667
//
1668
// For MAP, a partial projection represents value-subtree pruning only. The key child is not a
1669
// projected output shape; file readers still read full keys to construct ColumnMap offsets and keep
1670
// key semantics unchanged. If a caller tries to project only/prune the key child, the common schema
1671
// projection helper rejects it.
1672
55.5k
static Status build_complex_projection(const ColumnMapping& mapping, LocalColumnIndex* projection) {
1673
55.5k
    if (projection == nullptr) {
1674
0
        return Status::InvalidArgument("projection is null");
1675
0
    }
1676
55.5k
    DORIS_CHECK(mapping.file_local_id.has_value());
1677
55.5k
    *projection = LocalColumnIndex::local(*mapping.file_local_id);
1678
55.5k
    projection->project_all_children = mapping.child_mappings.empty();
1679
55.5k
    projection->children.clear();
1680
55.5k
    const auto present_children = present_child_mappings_in_file_order(mapping.child_mappings);
1681
55.5k
    if (!projection->project_all_children && present_children.empty()) {
1682
        // All requested table children under this complex node are missing/default-only. The file
1683
        // reader cannot expose an empty complex projection, but TableReader can still rematerialize
1684
        // the table shape from a full file subtree and fill the missing children with defaults.
1685
260
        projection->project_all_children = true;
1686
260
        return Status::OK();
1687
260
    }
1688
55.3k
    for (const auto* child_mapping : present_children) {
1689
19.6k
        LocalColumnIndex child_projection;
1690
19.6k
        RETURN_IF_ERROR(build_complex_projection(*child_mapping, &child_projection));
1691
19.6k
        projection->children.push_back(std::move(child_projection));
1692
19.6k
    }
1693
55.3k
    if (!projection->project_all_children && projection->children.empty()) {
1694
0
        return Status::NotSupported("Projection for complex column {} contains no file children",
1695
0
                                    mapping.file_column_name);
1696
0
    }
1697
55.3k
    return Status::OK();
1698
55.3k
}
1699
1700
using FilterProjectionMap = std::map<LocalColumnId, LocalColumnIndex>;
1701
1702
// Update the mapping's file type according to the projection, and determine whether the projection
1703
// is trivial (i.e. the projected file type is the same as the table type, so no need to
1704
// rematerialize the complex value back to table layout after reading from file).
1705
static Status apply_projection_to_mapping_file_type(const LocalColumnIndex& projection,
1706
507k
                                                    ColumnMapping* mapping) {
1707
507k
    DORIS_CHECK(mapping != nullptr);
1708
507k
    if (mapping->original_file_type == nullptr) {
1709
0
        mapping->original_file_type = mapping->file_type;
1710
0
    }
1711
507k
    if (mapping->original_file_type == nullptr ||
1712
507k
        !is_complex_type(remove_nullable(mapping->original_file_type)->get_primitive_type())) {
1713
329k
        return Status::OK();
1714
329k
    }
1715
177k
    ColumnDefinition field;
1716
177k
    field.type = mapping->original_file_type;
1717
177k
    field.children = mapping->original_file_children;
1718
177k
    ColumnDefinition projected_field;
1719
177k
    RETURN_IF_ERROR(project_column_definition(field, projection, &projected_field));
1720
177k
    mapping->file_type = std::move(projected_field.type);
1721
177k
    mapping->projected_file_children = std::move(projected_field.children);
1722
177k
    mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
1723
177k
    return Status::OK();
1724
177k
}
1725
1726
static Status merge_filter_projection(const FilterProjectionMap* filter_projections,
1727
75.5k
                                      LocalColumnIndex* projection) {
1728
75.5k
    DORIS_CHECK(projection != nullptr);
1729
75.5k
    if (filter_projections == nullptr) {
1730
0
        return Status::OK();
1731
0
    }
1732
75.5k
    const auto filter_projection_it = filter_projections->find(projection->column_id());
1733
75.5k
    if (filter_projection_it == filter_projections->end()) {
1734
74.2k
        return Status::OK();
1735
74.2k
    }
1736
    // Merge predicate-only nested paths into the root projection that is about to be scanned.
1737
    // Example: `SELECT s.a WHERE s.b > 1` first builds the output projection `s -> a` from
1738
    // ColumnMapping, while build_nested_struct_filter_projection_map() records `s -> b`. This merge
1739
    // produces one file scan projection `s -> a,b`.
1740
1.25k
    RETURN_IF_ERROR(merge_local_column_index(projection, filter_projection_it->second));
1741
1.25k
    return Status::OK();
1742
1.25k
}
1743
1744
172
static bool table_root_is_map(const ColumnMapping& mapping) {
1745
172
    if (mapping.table_type == nullptr) {
1746
0
        return false;
1747
0
    }
1748
172
    return remove_nullable(mapping.table_type)->get_primitive_type() == TYPE_MAP;
1749
172
}
1750
1751
static Status add_scan_column(FileScanRequest* file_request, ColumnMapping* mapping,
1752
                              bool is_predicate_column, bool force_full_complex_scan_projection,
1753
516k
                              const FilterProjectionMap* filter_projections = nullptr) {
1754
516k
    const auto file_column_id = LocalColumnId(mapping->file_local_id.value());
1755
516k
    LocalColumnIndex projection = LocalColumnIndex::top_level(file_column_id);
1756
    // Columnar readers can turn a complex mapping into a nested file projection, but
1757
    // row-oriented readers must scan the full top-level complex field because all children are
1758
    // encoded in the same text cell.
1759
516k
    if (!force_full_complex_scan_projection && needs_nested_file_projection(*mapping)) {
1760
5.88k
        RETURN_IF_ERROR(build_complex_projection(*mapping, &projection));
1761
5.88k
    }
1762
516k
    if (is_predicate_column && !force_full_complex_scan_projection) {
1763
75.5k
        DCHECK(filter_projections != nullptr);
1764
        // If a projected complex root is also used by a predicate, rebuild the predicate scan
1765
        // projection from the output mapping before merging predicate-only children. For
1766
        // `SELECT s.a WHERE s.b > 1`, build_complex_projection() produces `s -> a` and
1767
        // merge_filter_projection() adds `s -> b`, so the predicate column reads both children.
1768
75.5k
        RETURN_IF_ERROR(merge_filter_projection(filter_projections, &projection));
1769
75.5k
    }
1770
516k
    FileScanRequestBuilder builder(file_request);
1771
516k
    if (is_predicate_column) {
1772
75.5k
        return builder.add_predicate_column(std::move(projection));
1773
75.5k
    }
1774
440k
    return builder.add_non_predicate_column(std::move(projection));
1775
516k
}
1776
1777
static const LocalColumnIndex* find_scan_projection(
1778
946k
        const std::vector<LocalColumnIndex>& scan_columns, LocalColumnId file_column_id) {
1779
946k
    const auto projection_it =
1780
8.92M
            std::ranges::find_if(scan_columns, [&](const LocalColumnIndex& projection) {
1781
8.92M
                return projection.column_id() == file_column_id;
1782
8.92M
            });
1783
946k
    return projection_it == scan_columns.end() ? nullptr : &*projection_it;
1784
946k
}
1785
1786
// Apply the final scan projection of one root file column back to its ColumnMapping. This updates
1787
// mapping.file_type/projected_file_children from the original file schema to the exact shape that
1788
// FileReader will return.
1789
//
1790
// Example: for `SELECT s.a WHERE s.b > 1`, add_scan_column() keeps only one predicate scan
1791
// projection `s -> a,b`. Applying that projection changes the mapping's file type from the full
1792
// file struct `s<a,b,c>` to the projected file struct `s<a,b>`, so later filter rewrite and
1793
// TableReader final materialization use the same column shape as the file-local block.
1794
static Status apply_scan_projection_to_mapping_file_type(const FileScanRequest& file_request,
1795
507k
                                                         ColumnMapping* mapping) {
1796
507k
    DORIS_CHECK(mapping != nullptr);
1797
507k
    DORIS_CHECK(mapping->file_local_id.has_value());
1798
507k
    const auto file_column_id = LocalColumnId(*mapping->file_local_id);
1799
    // Predicate columns are the actual scan projection when a column is used by row-level filters:
1800
    // add_scan_column() removes the duplicate non-predicate projection in that case.
1801
507k
    const auto* projection = find_scan_projection(file_request.predicate_columns, file_column_id);
1802
507k
    if (projection == nullptr) {
1803
441k
        projection = find_scan_projection(file_request.non_predicate_columns, file_column_id);
1804
441k
    }
1805
507k
    DORIS_CHECK(projection != nullptr);
1806
507k
    return apply_projection_to_mapping_file_type(*projection, mapping);
1807
507k
}
1808
1809
// Build extra scan projections required only by row-level filters on nested struct children.
1810
//
1811
// Example: for `SELECT s.a FROM t WHERE s.b.c > 1`, the output projection may only contain `s.a`,
1812
// but the file reader must also read `s.b.c` to evaluate the predicate. This function collects the
1813
// table-side filter path, resolves it through ColumnMapping first, and records the corresponding
1814
// file-side projection in filter_projections. This keeps renamed fields consistent between the scan
1815
// projection and row-level conjunct rewrite. Example:
1816
//   table filter path: s -> renamed_b -> c
1817
//   old file path:     s -> b -> c
1818
//   recorded path:     s -> b -> c
1819
// When add_scan_column() adds the same root as a predicate column, it rebuilds that root from the
1820
// output mapping, merges this filter-only projection into it, and removes the duplicate
1821
// non-predicate root entry.
1822
static Status build_nested_struct_filter_projection_map(
1823
        const std::vector<TableFilter>& table_filters, const std::vector<ColumnMapping>& mappings,
1824
123k
        FilterProjectionMap* filter_projections) {
1825
123k
    DORIS_CHECK(filter_projections != nullptr);
1826
123k
    filter_projections->clear();
1827
123k
    for (const auto& table_filter : table_filters) {
1828
82.9k
        if (table_filter.conjunct == nullptr) {
1829
0
            continue;
1830
0
        }
1831
        // Collect all nested struct paths in the table filter. For example, for
1832
        // `s.id > 5 AND element_at(s, 'renamed_name') = 'abc'`, collect the table paths
1833
        // `s -> id` and `s -> renamed_name`, then resolve each one to its file-side projection.
1834
82.9k
        std::vector<NestedStructPath> paths;
1835
82.9k
        collect_nested_struct_paths(table_filter.conjunct->root(), &paths);
1836
82.9k
        for (const auto& path : paths) {
1837
5.43k
            auto mapping_it = std::ranges::find_if(mappings, [&](const ColumnMapping& mapping) {
1838
5.43k
                return mapping.global_index == path.root_global_index;
1839
5.43k
            });
1840
1.85k
            if (mapping_it == mappings.end() || !mapping_it->file_local_id.has_value() ||
1841
1.85k
                path.selectors.empty()) {
1842
440
                continue;
1843
440
            }
1844
1845
1.41k
            ResolvedNestedStructPath resolved;
1846
1.41k
            LocalColumnIndex root_projection;
1847
1.41k
            if (!resolve_nested_struct_path_for_file(path, mappings, &resolved)) {
1848
172
                if (!table_root_is_map(*mapping_it)) {
1849
171
                    continue;
1850
171
                }
1851
                // Direct map value filters such as `m.value.a > 1` need the value leaf for row
1852
                // evaluation even when the query only projects another value child. This is only a
1853
                // scan projection fallback; complex map/array expressions are still not rewritten
1854
                // into file-local conjuncts.
1855
1
                LocalColumnIndex child_projection;
1856
1
                RETURN_IF_ERROR(build_file_child_projection_from_schema(
1857
1
                        mapping_it->original_file_children, path.selectors, &child_projection));
1858
1
                if (child_projection.local_id() < 0) {
1859
0
                    continue;
1860
0
                }
1861
1
                root_projection = LocalColumnIndex::partial_local(*mapping_it->file_local_id);
1862
1
                root_projection.children.push_back(std::move(child_projection));
1863
1.24k
            } else {
1864
1.24k
                root_projection = std::move(resolved.file_projection);
1865
1.24k
            }
1866
1.24k
            auto filter_projection_it = filter_projections->find(root_projection.column_id());
1867
1.24k
            if (filter_projection_it == filter_projections->end()) {
1868
1.17k
                filter_projections->emplace(root_projection.column_id(),
1869
1.17k
                                            std::move(root_projection));
1870
1.17k
                continue;
1871
1.17k
            }
1872
68
            RETURN_IF_ERROR(
1873
68
                    merge_local_column_index(&filter_projection_it->second, root_projection));
1874
68
        }
1875
82.9k
    }
1876
123k
    return Status::OK();
1877
123k
}
1878
1879
506k
static void rebuild_projection(ColumnMapping* mapping, LocalIndex block_position) {
1880
506k
    DORIS_CHECK(mapping->file_local_id.has_value());
1881
506k
    if (mapping->is_trivial || needs_complex_rematerialize(*mapping)) {
1882
492k
        mapping->projection = VExprContext::create_shared(VSlotRef::create_shared(
1883
492k
                cast_set<int>(block_position.value()), cast_set<int>(block_position.value()), -1,
1884
492k
                mapping->file_type, mapping->file_column_name));
1885
492k
        return;
1886
492k
    }
1887
1888
13.8k
    auto expr = Cast::create_shared(mapping->table_type);
1889
13.8k
    expr->add_child(VSlotRef::create_shared(cast_set<int>(block_position.value()),
1890
13.8k
                                            cast_set<int>(block_position.value()), -1,
1891
13.8k
                                            mapping->file_type, mapping->file_column_name));
1892
13.8k
    mapping->projection = VExprContext::create_shared(expr);
1893
13.8k
}
1894
1895
// Build file slot rewrite info from the localized filter targets. Only local targets can enter
1896
// file-reader expressions; constant and unset targets stay above the file reader.
1897
static std::map<GlobalIndex, FileSlotRewriteInfo> build_file_slot_rewrite_map(
1898
        const std::vector<ColumnMapping>& mappings,
1899
123k
        const std::map<GlobalIndex, FilterEntry>& filter_entries) {
1900
123k
    std::map<GlobalIndex, FileSlotRewriteInfo> global_to_file_slot;
1901
533k
    for (const auto& mapping : mappings) {
1902
533k
        const auto entry_it = filter_entries.find(mapping.global_index);
1903
534k
        if (entry_it == filter_entries.end() || !entry_it->second.is_local()) {
1904
28.6k
            continue;
1905
28.6k
        }
1906
505k
        DORIS_CHECK(mapping.file_local_id.has_value());
1907
505k
        global_to_file_slot.emplace(
1908
505k
                mapping.global_index,
1909
505k
                FileSlotRewriteInfo {.block_position = entry_it->second.local_index().value(),
1910
505k
                                     .file_type = mapping.file_type,
1911
505k
                                     .table_type = mapping.table_type,
1912
505k
                                     .file_column_name = mapping.file_column_name});
1913
505k
    }
1914
123k
    return global_to_file_slot;
1915
123k
}
1916
1917
Status TableColumnMapper::_create_by_index_mapping(const ColumnDefinition& table_column,
1918
                                                   const std::vector<ColumnDefinition>& file_schema,
1919
36.9k
                                                   ColumnMapping* mapping) {
1920
36.9k
    DORIS_CHECK(mapping != nullptr);
1921
36.9k
    DORIS_CHECK(!table_column.is_partition_key);
1922
1923
    // Key contract: in BY_INDEX mode, `ColumnDefinition::identifier` TYPE_INT is interpreted as the
1924
    // 0-based position of this column inside `file_schema`. FE writes the physical file position
1925
    // of each non-partition projected column into that identifier. This interpretation allows:
1926
    //   - sparse projection: read only a subset of file columns (for example only `_col2`
1927
    //     and `_col4`);
1928
    //   - column reordering: table column order differs from file column order;
1929
    //   - no many-to-one mapping: FE must guarantee that each file position is referenced by at
1930
    //     most one table column.
1931
36.9k
    const auto file_index = table_column.get_identifier_position();
1932
1933
    // Case A: file_index is in range, so build a direct positional mapping.
1934
    // The file column name (for example `_col0`) is intentionally ignored here.
1935
36.9k
    if (file_index >= 0 && static_cast<size_t>(file_index) < file_schema.size()) {
1936
36.3k
        return _create_direct_mapping(table_column, file_schema[static_cast<size_t>(file_index)],
1937
36.3k
                                      mapping);
1938
36.3k
    }
1939
1940
    // Case B: file_index is out of range, which means the file does not contain this column.
1941
    // Route it through the missing-column path used by schema evolution.
1942
599
    if (table_column.default_expr != nullptr) {
1943
531
        _set_constant_mapping(mapping, table_column.default_expr);
1944
531
        return Status::OK();
1945
531
    }
1946
    // Keep the mapping empty (`file_local_id` remains `nullopt`) and let the upper finalize
1947
    // stage fill NULL/default values.
1948
68
    return Status::OK();
1949
599
}
1950
1951
23.1k
void TableColumnMapper::_set_constant_mapping(ColumnMapping* mapping, VExprContextSPtr expr) {
1952
23.1k
    DORIS_CHECK(mapping != nullptr);
1953
23.1k
    DORIS_CHECK(expr != nullptr);
1954
23.1k
    mapping->default_expr = std::move(expr);
1955
23.1k
    mapping->constant_index = _constant_map.add(ConstantEntry {
1956
23.1k
            .global_index = mapping->global_index,
1957
23.1k
            .expr = mapping->default_expr,
1958
23.1k
            .type = mapping->table_type,
1959
23.1k
    });
1960
23.1k
    mapping->filter_conversion = FilterConversionType::CONSTANT;
1961
23.1k
}
1962
1963
Status TableColumnMapper::_create_mapping_for_column(const ColumnDefinition& table_column,
1964
                                                     GlobalIndex global_index,
1965
532k
                                                     ColumnMapping* mapping) {
1966
532k
    DORIS_CHECK(mapping != nullptr);
1967
532k
    *mapping = ColumnMapping {};
1968
532k
    mapping->global_index = global_index;
1969
532k
    mapping->table_column_name = table_column.name;
1970
532k
    mapping->table_type = table_column.type;
1971
    // Row-lineage names are Iceberg metadata contracts, not reserved names in generic Hive,
1972
    // Hudi, or Paimon schemas. Only the Iceberg reader may opt into virtual synthesis.
1973
532k
    const auto row_lineage_type =
1974
532k
            _options.enable_row_lineage_virtual_columns
1975
532k
                    ? row_lineage_virtual_column_type(table_column, _options.mode)
1976
532k
                    : TableVirtualColumnType::INVALID;
1977
532k
    if (const auto* partition_value = find_partition_value(table_column, _partition_values);
1978
532k
        table_column.is_partition_key && partition_value != nullptr) {
1979
        // Partition values are split constants and must take precedence over defaults.
1980
16.1k
        _set_constant_mapping(mapping, VExprContext::create_shared(VLiteral::create_shared(
1981
16.1k
                                               mapping->table_type, *partition_value)));
1982
516k
    } else if (_options.mode == TableColumnMappingMode::BY_INDEX &&
1983
516k
               !table_column.is_partition_key && table_column.has_identifier_field_id()) {
1984
        // BY_INDEX interprets ColumnDefinition::identifier as physical file position.
1985
37.0k
        RETURN_IF_ERROR(_create_by_index_mapping(table_column, _file_schema, mapping));
1986
479k
    } else if (const auto* file_field = _find_file_field(table_column, _file_schema)) {
1987
        // Normal physical file column mapping.
1988
471k
        RETURN_IF_ERROR(_create_direct_mapping(table_column, *file_field, mapping));
1989
471k
        if (row_lineage_type != TableVirtualColumnType::INVALID) {
1990
            // Iceberg v3 rewritten files may physically contain row lineage metadata fields.
1991
            // File non-null values must be preserved, while file NULLs still inherit from data file
1992
            // metadata in IcebergTableReader. Therefore the mapping has a real file source plus a
1993
            // virtual post-materialization step, and filters must wait for finalize output.
1994
658
            mapping->virtual_column_type = row_lineage_type;
1995
658
            mapping->filter_conversion = FilterConversionType::FINALIZE_ONLY;
1996
658
        }
1997
471k
    } else if (row_lineage_type != TableVirtualColumnType::INVALID) {
1998
        // Iceberg row lineage metadata fields are optional in data files. Missing fields are exposed
1999
        // as all-NULL table columns first; IcebergTableReader fills inherited values only when the
2000
        // split carries first_row_id / last_updated_sequence_number metadata.
2001
        // FE may attach a default_expr to these hidden metadata columns, but the Iceberg v3
2002
        // inheritance rule must take precedence over the generic missing-column default path.
2003
3.19k
        mapping->virtual_column_type = row_lineage_type;
2004
5.40k
    } else if (table_column.name == BeConsts::ICEBERG_ROWID_COL) {
2005
        // Doris internal Iceberg row locator is never a physical Iceberg data column. It is built
2006
        // from file path, row position and partition metadata for delete/update/merge.
2007
546
        mapping->virtual_column_type = TableVirtualColumnType::ICEBERG_ROWID;
2008
6.44k
    } else if (table_column.default_expr != nullptr) {
2009
        // Table-format readers build typed default expressions before mapping. Keep that typed
2010
        // expression authoritative over the raw transport metadata, which cannot represent complex
2011
        // defaults safely in this table-format-neutral layer.
2012
6.44k
        _set_constant_mapping(mapping, table_column.default_expr);
2013
18.4E
    } else if (table_column.initial_default_value.has_value()) {
2014
0
        return Status::InvalidArgument(
2015
0
                "Missing typed initial-default expression for table field '{}'", table_column.name);
2016
18.4E
    } else if (_options.reject_missing_required_field && table_column.is_optional.has_value() &&
2017
18.4E
               !*table_column.is_optional) {
2018
1
        return Status::InvalidArgument("Missing required field: {}", table_column.name);
2019
18.4E
    } else {
2020
18.4E
        if (table_column.is_partition_key) {
2021
0
            return Status::InvalidArgument(
2022
0
                    "Table column '{}' (global_index={}) does not have a matching partition value",
2023
0
                    table_column.name, mapping->global_index.value());
2024
0
        }
2025
18.4E
    }
2026
532k
    return Status::OK();
2027
532k
}
2028
2029
Status TableColumnMapper::_create_hidden_filter_mapping(const ColumnDefinition& table_column,
2030
                                                        GlobalIndex global_index,
2031
2
                                                        ColumnMapping* mapping) {
2032
2
    auto status = _create_mapping_for_column(table_column, global_index, mapping);
2033
2
    if (mapping->file_local_id.has_value() || mapping->constant_index.has_value() ||
2034
2
        mapping->virtual_column_type != TableVirtualColumnType::INVALID) {
2035
0
        return Status::OK();
2036
0
    }
2037
2
    if (_options.mode == TableColumnMappingMode::BY_NAME) {
2038
0
        return status;
2039
0
    }
2040
2041
    // Predicate-only slot refs carry the table name/type but do not carry the table-format field
2042
    // id used by BY_FIELD_ID or the file position used by BY_INDEX. Use a name fallback only for
2043
    // hidden filter localization; projected columns still obey the requested mapping mode.
2044
2
    const auto* file_field =
2045
2
            matcher_for_mode(TableColumnMappingMode::BY_NAME).find(table_column, _file_schema);
2046
2
    if (file_field == nullptr) {
2047
0
        return status;
2048
0
    }
2049
2
    ColumnMapping fallback_mapping;
2050
2
    fallback_mapping.global_index = global_index;
2051
2
    fallback_mapping.table_column_name = table_column.name;
2052
2
    fallback_mapping.table_type = table_column.type;
2053
2
    RETURN_IF_ERROR(_create_direct_mapping(table_column, *file_field, &fallback_mapping));
2054
2
    *mapping = std::move(fallback_mapping);
2055
2
    return Status::OK();
2056
2
}
2057
2058
Status TableColumnMapper::_build_hidden_filter_mappings(
2059
123k
        const std::vector<TableFilter>& table_filters) {
2060
123k
    _hidden_mappings.clear();
2061
2062
123k
    std::map<GlobalIndex, ColumnDefinition> filter_columns;
2063
123k
    for (const auto& table_filter : table_filters) {
2064
82.9k
        if (table_filter.conjunct != nullptr) {
2065
82.9k
            collect_top_level_slot_columns(table_filter.conjunct->root(), &filter_columns);
2066
82.9k
        }
2067
82.9k
    }
2068
2069
123k
    for (const auto& [global_index, table_column] : filter_columns) {
2070
71.8k
        if (_find_mapping(global_index) != nullptr) {
2071
            // Ignore columns that are already mapped by the projected columns
2072
71.8k
            continue;
2073
71.8k
        }
2074
6
        ColumnMapping mapping;
2075
6
        RETURN_IF_ERROR(_create_hidden_filter_mapping(table_column, global_index, &mapping));
2076
6
        if (mapping.file_local_id.has_value() || mapping.constant_index.has_value() ||
2077
6
            mapping.virtual_column_type != TableVirtualColumnType::INVALID) {
2078
2
            _hidden_mappings.push_back(std::move(mapping));
2079
2
        }
2080
6
    }
2081
123k
    return Status::OK();
2082
123k
}
2083
2084
Status TableColumnMapper::create_mapping(const std::vector<ColumnDefinition>& projected_columns,
2085
                                         const std::map<std::string, Field>& partition_values,
2086
123k
                                         const std::vector<ColumnDefinition>& file_schema) {
2087
123k
    clear();
2088
123k
    _partition_values = partition_values;
2089
123k
    _file_schema = file_schema;
2090
657k
    for (size_t column_idx = 0; column_idx < projected_columns.size(); ++column_idx) {
2091
534k
        ColumnMapping mapping;
2092
534k
        RETURN_IF_ERROR(_create_mapping_for_column(projected_columns[column_idx],
2093
534k
                                                   GlobalIndex(column_idx), &mapping));
2094
534k
        _mappings.push_back(std::move(mapping));
2095
534k
    }
2096
123k
    return Status::OK();
2097
123k
}
2098
2099
369k
std::vector<ColumnMapping> TableColumnMapper::_filter_visible_mappings() const {
2100
369k
    std::vector<ColumnMapping> mappings;
2101
369k
    mappings.reserve(_mappings.size() + _hidden_mappings.size());
2102
369k
    mappings.insert(mappings.end(), _mappings.begin(), _mappings.end());
2103
369k
    mappings.insert(mappings.end(), _hidden_mappings.begin(), _hidden_mappings.end());
2104
369k
    return mappings;
2105
369k
}
2106
2107
122k
Status TableColumnMapper::_build_filter_entries(const FileScanRequest& file_request) {
2108
122k
    _filter_entries.clear();
2109
122k
    const auto mappings = _filter_visible_mappings();
2110
534k
    for (const auto& mapping : mappings) {
2111
534k
        FilterEntry entry;
2112
534k
        if (mapping.constant_index.has_value()) {
2113
23.1k
            entry = FilterEntry::constant(*mapping.constant_index);
2114
511k
        } else if (mapping.file_local_id.has_value() &&
2115
511k
                   filter_conversion_has_local_source(mapping.filter_conversion)) {
2116
506k
            const auto local_position_it =
2117
506k
                    file_request.local_positions.find(LocalColumnId(*mapping.file_local_id));
2118
506k
            if (local_position_it != file_request.local_positions.end()) {
2119
506k
                entry = FilterEntry::local(local_position_it->second);
2120
506k
            }
2121
506k
        }
2122
534k
        _filter_entries.emplace(mapping.global_index, entry);
2123
534k
    }
2124
122k
    return Status::OK();
2125
122k
}
2126
2127
Status TableColumnMapper::create_scan_request(
2128
        const std::vector<TableFilter>& table_filters,
2129
        const std::vector<ColumnDefinition>& projected_columns, FileScanRequest* file_request,
2130
123k
        RuntimeState* runtime_state) {
2131
    // FileReader evaluates expressions against a file-local block. This mapper owns the
2132
    // table-column to file-column conversion, so it also owns the file-local block positions.
2133
123k
    file_request->predicate_columns.clear();
2134
123k
    file_request->non_predicate_columns.clear();
2135
123k
    file_request->predicate_only_columns.clear();
2136
123k
    file_request->local_positions.clear();
2137
123k
    file_request->conjuncts.clear();
2138
123k
    file_request->delete_conjuncts.clear();
2139
123k
    _filter_entries.clear();
2140
    // 1. Build referenced non-predicate columns
2141
656k
    for (size_t column_idx = 0; column_idx < projected_columns.size(); ++column_idx) {
2142
533k
        const auto global_index = GlobalIndex(column_idx);
2143
533k
        auto* mapping = _find_mapping(global_index);
2144
533k
        if (mapping != nullptr && mapping->file_local_id.has_value()) {
2145
            // A file column can be read lazily as a non-predicate column only when it is not used
2146
            // by row-level expression filters.
2147
506k
            bool used_by_filter = false;
2148
506k
            for (const auto& table_filter : table_filters) {
2149
146k
                const auto& global_indices = table_filter.global_indices;
2150
146k
                if (std::find(global_indices.begin(), global_indices.end(), global_index) !=
2151
146k
                            global_indices.end() &&
2152
146k
                    filter_conversion_has_local_source(mapping->filter_conversion)) {
2153
65.2k
                    used_by_filter = true;
2154
65.2k
                    break;
2155
65.2k
                }
2156
146k
            }
2157
506k
            if (!used_by_filter || !enable_lazy_materialization()) {
2158
441k
                RETURN_IF_ERROR(add_scan_column(file_request, mapping, false,
2159
441k
                                                force_full_complex_scan_projection()));
2160
441k
            }
2161
506k
        }
2162
533k
    }
2163
    // 2. Build referenced predicate columns
2164
    // Hidden filter mappings must be built before localizing filters, so that they can be localized together with visible mappings and referenced by localized filter expressions.
2165
123k
    RETURN_IF_ERROR(_build_hidden_filter_mappings(table_filters));
2166
123k
    RETURN_IF_ERROR(localize_filters(table_filters, file_request, runtime_state));
2167
123k
    for (const auto& mapping : _hidden_mappings) {
2168
2
        if (!mapping.file_local_id.has_value()) {
2169
0
            continue;
2170
0
        }
2171
2
        const auto local_id = LocalColumnId(*mapping.file_local_id);
2172
2
        const bool is_visible_output =
2173
2
                std::ranges::any_of(_mappings, [local_id](const ColumnMapping& visible_mapping) {
2174
2
                    return visible_mapping.file_local_id.has_value() &&
2175
2
                           LocalColumnId(*visible_mapping.file_local_id) == local_id;
2176
2
                });
2177
2
        if (is_visible_output) {
2178
0
            continue;
2179
0
        }
2180
        // File-local filtering is an optimization; Scanner still evaluates the original
2181
        // table-level conjunct after TableReader returns. Only truly hidden mappings are absent
2182
        // from that scanner-visible block and may safely discard their payload here.
2183
2
        if (std::ranges::any_of(file_request->predicate_columns,
2184
2
                                [local_id](const LocalColumnIndex& projection) {
2185
2
                                    return projection.column_id() == local_id;
2186
2
                                }) &&
2187
2
            !file_request->is_predicate_only(local_id)) {
2188
2
            file_request->predicate_only_columns.push_back(local_id);
2189
2
        }
2190
2
    }
2191
    // 3. Rebuild output projection expressions for projected columns. localize_filters() has
2192
    // already applied the final scan projection to mapping.file_type/projected_file_children before
2193
    // rewriting filter expressions.
2194
532k
    for (auto& mapping : _mappings) {
2195
532k
        if (!mapping.file_local_id.has_value()) {
2196
26.8k
            continue;
2197
26.8k
        }
2198
505k
        auto position_it =
2199
505k
                file_request->local_positions.find(LocalColumnId(*mapping.file_local_id));
2200
18.4E
        DORIS_CHECK(position_it != file_request->local_positions.end())
2201
18.4E
                << file_request->local_positions.size() << " " << *mapping.file_local_id << " "
2202
18.4E
                << mapping.file_column_name;
2203
505k
        rebuild_projection(&mapping, position_it->second);
2204
505k
    }
2205
123k
    return Status::OK();
2206
123k
}
2207
2208
761k
ColumnMapping* TableColumnMapper::_find_mapping(GlobalIndex global_index) {
2209
9.41M
    for (auto& mapping : _mappings) {
2210
9.41M
        if (mapping.global_index == global_index) {
2211
762k
            return &mapping;
2212
762k
        }
2213
9.41M
    }
2214
18.4E
    return nullptr;
2215
761k
}
2216
2217
157k
ColumnMapping* TableColumnMapper::_find_filter_mapping(GlobalIndex global_index) {
2218
157k
    if (auto* mapping = _find_mapping(global_index); mapping != nullptr) {
2219
157k
        return mapping;
2220
157k
    }
2221
18.4E
    for (auto& mapping : _hidden_mappings) {
2222
4
        if (mapping.global_index == global_index) {
2223
4
            return &mapping;
2224
4
        }
2225
4
    }
2226
18.4E
    return nullptr;
2227
18.4E
}
2228
2229
Status TableColumnMapper::localize_filters(const std::vector<TableFilter>& table_filters,
2230
                                           FileScanRequest* file_request,
2231
123k
                                           RuntimeState* runtime_state) {
2232
123k
    std::set<LocalColumnId> localized_predicate_columns;
2233
123k
    FilterProjectionMap filter_projections;
2234
123k
    auto filter_mappings = _filter_visible_mappings();
2235
123k
    RETURN_IF_ERROR(build_nested_struct_filter_projection_map(table_filters, filter_mappings,
2236
123k
                                                              &filter_projections));
2237
123k
    for (const auto& table_filter : table_filters) {
2238
84.2k
        for (const auto& global_index : table_filter.global_indices) {
2239
84.2k
            auto* mapping = _find_filter_mapping(global_index);
2240
84.2k
            if (mapping == nullptr || !mapping->file_local_id.has_value() ||
2241
84.2k
                !filter_conversion_has_local_source(mapping->filter_conversion)) {
2242
8.39k
                continue;
2243
8.39k
            }
2244
75.8k
            RETURN_IF_ERROR(add_scan_column(file_request, mapping, enable_lazy_materialization(),
2245
75.8k
                                            force_full_complex_scan_projection(),
2246
75.8k
                                            &filter_projections));
2247
75.8k
        }
2248
82.9k
    }
2249
    // Rebuild the file type for every scan-local mapping before expression rewrite. Predicate-only
2250
    // hidden mappings must see the same projected file type as the file reader will produce.
2251
533k
    for (auto& mapping : _mappings) {
2252
533k
        if (mapping.file_local_id.has_value() &&
2253
533k
            file_request->local_positions.contains(LocalColumnId(*mapping.file_local_id))) {
2254
507k
            RETURN_IF_ERROR(apply_scan_projection_to_mapping_file_type(*file_request, &mapping));
2255
507k
        }
2256
533k
    }
2257
123k
    for (auto& mapping : _hidden_mappings) {
2258
2
        if (mapping.file_local_id.has_value() &&
2259
2
            file_request->local_positions.contains(LocalColumnId(*mapping.file_local_id))) {
2260
2
            RETURN_IF_ERROR(apply_scan_projection_to_mapping_file_type(*file_request, &mapping));
2261
2
        }
2262
2
    }
2263
123k
    RETURN_IF_ERROR(_build_filter_entries(*file_request));
2264
2265
    // Build the complete table-slot rewrite map after all predicate columns have been assigned.
2266
    // This keeps expression localization independent from filter iteration order.
2267
123k
    filter_mappings = _filter_visible_mappings();
2268
123k
    const auto global_to_file_slot = build_file_slot_rewrite_map(filter_mappings, _filter_entries);
2269
123k
    for (const auto& table_filter : table_filters) {
2270
83.1k
        if (table_filter.conjunct != nullptr && table_filter.conjunct->root() != nullptr) {
2271
83.1k
            const auto root = table_filter.conjunct->root();
2272
83.1k
            const auto impl = root->get_impl();
2273
83.1k
            const auto predicate = impl != nullptr ? impl : root;
2274
83.1k
            if (!predicate->is_deterministic() ||
2275
83.1k
                !table_filter_has_only_local_entries(table_filter, _filter_entries)) {
2276
8.16k
                continue;
2277
8.16k
            }
2278
            // Scanner evaluates the original conjunct after final materialization. Only predicates
2279
            // whose result is stable across repeated execution may also run as a file-local copy.
2280
74.9k
            RewriteContext rewrite_context {.runtime_state = runtime_state};
2281
74.9k
            VExprSPtr rewrite_root;
2282
74.9k
            Status clone_status;
2283
74.9k
            try {
2284
74.9k
                clone_status = clone_table_expr_tree(table_filter.conjunct->root(), &rewrite_root);
2285
74.9k
            } catch ([[maybe_unused]] const Exception& e) {
2286
                // Some table filters contain complex intermediate values, for example
2287
                // `element_at(MAP_VALUES(m)[1], 'age') > 30`. The current file-local rewrite only
2288
                // understands top-level slots and struct-element paths rooted at top-level slots;
2289
                // cloning such expressions can hit the generic TExpr complex-type limitation.
2290
                // Leave them above TableReader, where Scanner evaluates the original table-level
2291
                // conjunct after final materialization.
2292
0
#ifndef NDEBUG
2293
0
                return Status::InternalError(
2294
0
                        "Failed to clone table filter for file-local rewrite: {}, expr={}",
2295
0
                        e.to_string(), table_filter.conjunct->root()->debug_string());
2296
#else
2297
                continue;
2298
#endif
2299
0
            } catch ([[maybe_unused]] const std::exception& e) {
2300
0
#ifndef NDEBUG
2301
0
                return Status::InternalError(
2302
0
                        "Failed to clone table filter for file-local rewrite: {}, expr={}",
2303
0
                        e.what(), table_filter.conjunct->root()->debug_string());
2304
#else
2305
                continue;
2306
#endif
2307
0
            }
2308
74.9k
            if (!clone_status.ok()) {
2309
0
#ifndef NDEBUG
2310
0
                return Status::InternalError(
2311
0
                        "Failed to clone table filter for file-local rewrite: {}, expr={}",
2312
0
                        clone_status.to_string(), table_filter.conjunct->root()->debug_string());
2313
#else
2314
                continue;
2315
#endif
2316
0
            }
2317
74.9k
            bool can_localize = true;
2318
74.9k
            auto localized_root = rewrite_table_expr_to_file_expr(rewrite_root, global_to_file_slot,
2319
74.9k
                                                                  filter_mappings, &rewrite_context,
2320
74.9k
                                                                  &can_localize);
2321
74.9k
            if (!can_localize) {
2322
2.59k
                continue;
2323
2.59k
            }
2324
72.3k
            auto localized_conjunct = VExprContext::create_shared(std::move(localized_root));
2325
72.3k
            RETURN_IF_ERROR(rewrite_context.prepare_created_exprs(localized_conjunct.get()));
2326
72.3k
            file_request->conjuncts.push_back(std::move(localized_conjunct));
2327
72.9k
            for (const auto global_index : table_filter.global_indices) {
2328
72.9k
                const auto* mapping = _find_filter_mapping(global_index);
2329
72.9k
                if (mapping != nullptr && mapping->file_local_id.has_value() &&
2330
72.9k
                    filter_conversion_has_local_source(mapping->filter_conversion)) {
2331
72.9k
                    localized_predicate_columns.emplace(*mapping->file_local_id);
2332
72.9k
                }
2333
72.9k
            }
2334
72.3k
        }
2335
82.9k
    }
2336
2337
    // Candidate columns are added before expression rewriting because their file-block positions
2338
    // are needed to localize slot refs. If rewriting rejects every filter that references a visible
2339
    // column, move its already-merged output/filter projection to the lazy non-predicate set
2340
    // instead of forcing it through the eager predicate path.
2341
533k
    for (auto& mapping : _mappings) {
2342
533k
        if (!mapping.file_local_id.has_value()) {
2343
26.8k
            continue;
2344
26.8k
        }
2345
506k
        const auto local_id = LocalColumnId(*mapping.file_local_id);
2346
506k
        if (localized_predicate_columns.contains(local_id)) {
2347
62.2k
            continue;
2348
62.2k
        }
2349
444k
        const auto predicate_it = std::ranges::find_if(
2350
444k
                file_request->predicate_columns, [local_id](const LocalColumnIndex& projection) {
2351
60.9k
                    return projection.column_id() == local_id;
2352
60.9k
                });
2353
444k
        if (predicate_it == file_request->predicate_columns.end()) {
2354
442k
            continue;
2355
442k
        }
2356
2.38k
        file_request->non_predicate_columns.push_back(std::move(*predicate_it));
2357
2.38k
        file_request->predicate_columns.erase(predicate_it);
2358
2.38k
    }
2359
123k
    return Status::OK();
2360
123k
}
2361
2362
const ColumnDefinition* TableColumnMapper::_find_file_field(
2363
        const ColumnDefinition& table_column,
2364
483k
        const std::vector<ColumnDefinition>& file_schema) const {
2365
483k
    if (table_column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
2366
1.04M
        const auto field_it = std::ranges::find_if(file_schema, [](const ColumnDefinition& field) {
2367
1.04M
            return field.column_type == ColumnType::GLOBAL_ROWID;
2368
1.04M
        });
2369
7.46k
        return field_it == file_schema.end() ? nullptr : &*field_it;
2370
7.46k
    }
2371
476k
    const auto* matched = matcher_for_mode(_options.mode).find(table_column, file_schema);
2372
476k
    if (matched != nullptr || _options.mode != TableColumnMappingMode::BY_FIELD_ID ||
2373
476k
        !_options.allow_idless_complex_wrapper_projection || table_column.children.empty()) {
2374
475k
        return matched;
2375
475k
    }
2376
836
    const ColumnDefinition* wrapper = nullptr;
2377
3.44k
    for (const auto& candidate : file_schema) {
2378
3.44k
        if (candidate.has_identifier_field_id() || candidate.children.empty() ||
2379
3.44k
            !has_shared_descendant_field_id(table_column, candidate)) {
2380
3.42k
            continue;
2381
3.42k
        }
2382
12
        if (wrapper != nullptr) {
2383
0
            return nullptr;
2384
0
        }
2385
12
        wrapper = &candidate;
2386
12
    }
2387
    // Iceberg Parquet's PruneColumns retains an ID-less complex wrapper when a nested field ID is
2388
    // selected. Descendant IDs, not aliases, identify that wrapper; ambiguity remains unmapped.
2389
836
    return wrapper;
2390
836
}
2391
2392
Status TableColumnMapper::_create_direct_mapping(const ColumnDefinition& table_column,
2393
                                                 const ColumnDefinition& file_field,
2394
830k
                                                 ColumnMapping* mapping) const {
2395
830k
    DORIS_CHECK(mapping != nullptr);
2396
830k
    DORIS_CHECK(file_field.local_id >= 0 || file_field.local_id == GLOBAL_ROWID_COLUMN_ID);
2397
830k
    mapping->file_local_id = file_field.local_id;
2398
830k
    mapping->table_column_name = table_column.name;
2399
830k
    mapping->file_column_name = file_field.name;
2400
830k
    mapping->original_file_type = file_field.type;
2401
830k
    mapping->original_file_children = file_field.children;
2402
830k
    mapping->projected_file_children = file_field.children;
2403
830k
    mapping->file_type = file_field.type;
2404
830k
    mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
2405
830k
    mapping->filter_conversion = direct_filter_conversion(*mapping);
2406
830k
    mapping->child_mappings.clear();
2407
2408
830k
    auto [table_children, synthesized_table_children] =
2409
830k
            prepare_table_children_for_mapping(table_column, mapping->file_type);
2410
2411
830k
    if (!table_children.empty()) {
2412
208k
        if (!is_complex_type(remove_nullable(mapping->file_type)->get_primitive_type())) {
2413
0
            return Status::NotSupported(
2414
0
                    "Cannot map complex table column '{}' to scalar parquet column '{}', table "
2415
0
                    "type={}, file type={}",
2416
0
                    table_column.name, file_field.name, mapping->table_type->get_name(),
2417
0
                    mapping->file_type->get_name());
2418
0
        }
2419
208k
        RETURN_IF_ERROR(validate_file_schema_children(file_field));
2420
208k
        std::vector<int32_t> synthesized_used_file_child_ids;
2421
537k
        for (size_t table_child_idx = 0; table_child_idx < table_children.size();
2422
329k
             ++table_child_idx) {
2423
329k
            const auto& table_child = table_children[table_child_idx];
2424
329k
            const auto* file_child =
2425
329k
                    find_file_child_for_mapping(table_child, file_field, _options.mode,
2426
329k
                                                table_child_idx, synthesized_table_children);
2427
329k
            if (file_child == nullptr && !synthesized_table_children &&
2428
329k
                _options.mode == TableColumnMappingMode::BY_FIELD_ID &&
2429
329k
                _options.allow_idless_complex_wrapper_projection) {
2430
                // Parquet can retain an ID-less wrapper at any depth when a selected descendant
2431
                // has an ID; apply the same opt-in fallback used for root lookup recursively.
2432
2.43k
                file_child = _find_file_field(table_child, file_field.children);
2433
2.43k
            }
2434
329k
            if (synthesized_table_children && file_child != nullptr) {
2435
8
                const auto file_child_id = file_child->file_local_id();
2436
8
                if (std::ranges::find(synthesized_used_file_child_ids, file_child_id) !=
2437
8
                    synthesized_used_file_child_ids.end()) {
2438
2
                    file_child = nullptr;
2439
2
                    for (const auto& candidate : file_field.children) {
2440
2
                        const auto candidate_id = candidate.file_local_id();
2441
2
                        if (std::ranges::find(synthesized_used_file_child_ids, candidate_id) ==
2442
2
                            synthesized_used_file_child_ids.end()) {
2443
2
                            file_child = &candidate;
2444
2
                            break;
2445
2
                        }
2446
2
                    }
2447
2
                }
2448
8
                if (file_child != nullptr) {
2449
8
                    synthesized_used_file_child_ids.push_back(file_child->file_local_id());
2450
8
                }
2451
8
            }
2452
329k
            if (file_child == nullptr) {
2453
5.60k
                if (table_child.default_expr == nullptr &&
2454
5.60k
                    table_child.initial_default_value.has_value()) {
2455
0
                    return Status::InvalidArgument(
2456
0
                            "Missing typed initial-default expression for table field '{}'",
2457
0
                            table_child.name);
2458
0
                }
2459
5.60k
                if (_options.reject_missing_required_field && table_child.is_optional.has_value() &&
2460
5.60k
                    !*table_child.is_optional && table_child.default_expr == nullptr) {
2461
1
                    return Status::InvalidArgument("Missing required field: {}", table_child.name);
2462
1
                }
2463
5.60k
                ColumnMapping child_mapping;
2464
5.60k
                child_mapping.table_column_name = table_child.name;
2465
5.60k
                child_mapping.file_column_name = table_child.name;
2466
5.60k
                child_mapping.table_type = table_child.type;
2467
5.60k
                child_mapping.file_type = table_child.type;
2468
5.60k
                child_mapping.default_expr = table_child.default_expr;
2469
5.60k
                child_mapping.filter_conversion = FilterConversionType::FINALIZE_ONLY;
2470
5.60k
                mapping->child_mappings.push_back(std::move(child_mapping));
2471
5.60k
                continue;
2472
5.60k
            }
2473
323k
            ColumnMapping child_mapping;
2474
323k
            child_mapping.table_column_name = table_child.name;
2475
323k
            child_mapping.table_type = table_child.type;
2476
323k
            RETURN_IF_ERROR(_create_direct_mapping(table_child, *file_child, &child_mapping));
2477
323k
            mapping->child_mappings.push_back(std::move(child_mapping));
2478
323k
        }
2479
208k
        if (needs_projected_file_type_rebuild(*mapping)) {
2480
            // If complex projection prunes some children, we have to rebuild the projected file type to make sure the reader expression can find the correct child types by name.
2481
19.7k
            RETURN_IF_ERROR(rebuild_projected_file_children_and_type(
2482
19.7k
                    mapping->file_type, mapping->original_file_children, mapping->child_mappings,
2483
19.7k
                    &mapping->projected_file_children, &mapping->file_type));
2484
19.7k
            DCHECK(mapping->table_type != nullptr);
2485
19.7k
            mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
2486
19.7k
            mapping->filter_conversion = projected_filter_conversion(*mapping);
2487
19.7k
        }
2488
208k
    }
2489
830k
    return Status::OK();
2490
830k
}
2491
2492
} // namespace doris::format