Coverage Report

Created: 2026-08-06 13:04

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