Coverage Report

Created: 2026-08-06 12:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format_v2/table_reader.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "format_v2/table_reader.h"
19
20
#include <gen_cpp/ExternalTableSchema_types.h>
21
#include <gen_cpp/PlanNodes_types.h>
22
#include <gen_cpp/Types_types.h>
23
24
#include <algorithm>
25
#include <memory>
26
#include <ranges>
27
#include <set>
28
#include <sstream>
29
#include <utility>
30
#include <vector>
31
32
#include "common/cast_set.h"
33
#include "common/status.h"
34
#include "core/assert_cast.h"
35
#include "core/data_type/data_type_array.h"
36
#include "core/data_type/data_type_factory.hpp"
37
#include "core/data_type/data_type_map.h"
38
#include "core/data_type/data_type_struct.h"
39
#include "core/data_type/primitive_type.h"
40
#include "exprs/vexpr_context.h"
41
#include "exprs/vslot_ref.h"
42
#include "format/table/deletion_vector_reader.h"
43
#include "format/table/iceberg_delete_file_reader_helper.h"
44
#include "format/table/iceberg_scan_semantics.h"
45
#include "format/table/paimon_reader.h"
46
#include "format_v2/column_mapper.h"
47
#include "format_v2/delimited_text/csv_reader.h"
48
#include "format_v2/delimited_text/text_reader.h"
49
#include "format_v2/json/json_reader.h"
50
#include "format_v2/native/native_reader.h"
51
#include "format_v2/orc/orc_reader.h"
52
#include "format_v2/parquet/parquet_reader.h"
53
#include "runtime/file_scan_profile.h"
54
#include "storage/segment/condition_cache.h"
55
#include "util/debug_points.h"
56
#include "util/string_util.h"
57
58
namespace doris::format {
59
namespace {
60
61
template <typename T, typename Formatter>
62
61
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
63
61
    std::ostringstream out;
64
61
    out << "[";
65
70
    for (size_t i = 0; i < values.size(); ++i) {
66
9
        if (i > 0) {
67
3
            out << ", ";
68
3
        }
69
9
        out << formatter(values[i]);
70
9
    }
71
61
    out << "]";
72
61
    return out.str();
73
61
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_16ColumnDefinitionEZNKS0_11TableReader12debug_stringB5cxx11EvE3$_0EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
62
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
63
12
    std::ostringstream out;
64
12
    out << "[";
65
14
    for (size_t i = 0; i < values.size(); ++i) {
66
2
        if (i > 0) {
67
1
            out << ", ";
68
1
        }
69
2
        out << formatter(values[i]);
70
2
    }
71
12
    out << "]";
72
12
    return out.str();
73
12
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_11TableFilterEZNKS0_11TableReader12debug_stringB5cxx11EvE3$_1EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
62
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
63
12
    std::ostringstream out;
64
12
    out << "[";
65
13
    for (size_t i = 0; i < values.size(); ++i) {
66
1
        if (i > 0) {
67
0
            out << ", ";
68
0
        }
69
1
        out << formatter(values[i]);
70
1
    }
71
12
    out << "]";
72
12
    return out.str();
73
12
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_11GlobalIndexEZNS1_25table_filter_debug_stringB5cxx11ERKNS0_11TableFilterEE3$_0EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISF_EET0_
Line
Count
Source
62
1
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
63
1
    std::ostringstream out;
64
1
    out << "[";
65
2
    for (size_t i = 0; i < values.size(); ++i) {
66
1
        if (i > 0) {
67
0
            out << ", ";
68
0
        }
69
1
        out << formatter(values[i]);
70
1
    }
71
1
    out << "]";
72
1
    return out.str();
73
1
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsISt10shared_ptrINS_12VExprContextEEZNKS0_11TableReader12debug_stringB5cxx11EvE3$_2EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISF_EET0_
Line
Count
Source
62
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
63
12
    std::ostringstream out;
64
12
    out << "[";
65
13
    for (size_t i = 0; i < values.size(); ++i) {
66
1
        if (i > 0) {
67
0
            out << ", ";
68
0
        }
69
1
        out << formatter(values[i]);
70
1
    }
71
12
    out << "]";
72
12
    return out.str();
73
12
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_16ColumnDefinitionEZNKS0_11TableReader12debug_stringB5cxx11EvE3$_3EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
62
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
63
12
    std::ostringstream out;
64
12
    out << "[";
65
14
    for (size_t i = 0; i < values.size(); ++i) {
66
2
        if (i > 0) {
67
1
            out << ", ";
68
1
        }
69
2
        out << formatter(values[i]);
70
2
    }
71
12
    out << "]";
72
12
    return out.str();
73
12
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_11TableReader15FileBlockColumnEZNKS3_12debug_stringB5cxx11EvE3$_4EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
62
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
63
12
    std::ostringstream out;
64
12
    out << "[";
65
14
    for (size_t i = 0; i < values.size(); ++i) {
66
2
        if (i > 0) {
67
1
            out << ", ";
68
1
        }
69
2
        out << formatter(values[i]);
70
2
    }
71
12
    out << "]";
72
12
    return out.str();
73
12
}
74
75
12
std::string file_format_to_string(FileFormat format) {
76
12
    switch (format) {
77
5
    case FileFormat::PARQUET:
78
5
        return "PARQUET";
79
1
    case FileFormat::ORC:
80
1
        return "ORC";
81
1
    case FileFormat::CSV:
82
1
        return "CSV";
83
1
    case FileFormat::JSON:
84
1
        return "JSON";
85
1
    case FileFormat::TEXT:
86
1
        return "TEXT";
87
1
    case FileFormat::JNI:
88
1
        return "JNI";
89
1
    case FileFormat::NATIVE:
90
1
        return "NATIVE";
91
1
    case FileFormat::ARROW:
92
1
        return "ARROW";
93
0
    case FileFormat::WAL:
94
0
        return "WAL";
95
12
    }
96
0
    return "UNKNOWN";
97
12
}
98
99
12
std::string push_down_agg_to_string(TPushAggOp::type op) {
100
12
    switch (op) {
101
8
    case TPushAggOp::NONE:
102
8
        return "NONE";
103
1
    case TPushAggOp::COUNT:
104
1
        return "COUNT";
105
1
    case TPushAggOp::MINMAX:
106
1
        return "MINMAX";
107
1
    case TPushAggOp::MIX:
108
1
        return "MIX";
109
1
    case TPushAggOp::COUNT_ON_INDEX:
110
1
        return "COUNT_ON_INDEX";
111
12
    }
112
0
    return "UNKNOWN";
113
12
}
114
115
12
std::string current_file_debug_string(const std::unique_ptr<ScanTask>& task) {
116
12
    if (task == nullptr || task->data_file == nullptr) {
117
11
        return "null";
118
11
    }
119
1
    const auto& file = *task->data_file;
120
1
    std::ostringstream out;
121
1
    out << "FileDescription{path=" << file.path << ", file_size=" << file.file_size
122
1
        << ", range_start_offset=" << file.range_start_offset << ", range_size=" << file.range_size
123
1
        << ", mtime=" << file.mtime << ", fs_name=" << file.fs_name
124
1
        << ", is_immutable=" << file.is_immutable
125
1
        << ", file_cache_admission=" << file.file_cache_admission << "}";
126
1
    return out.str();
127
12
}
128
129
12
std::string partition_values_debug_string(const std::map<std::string, Field>& partition_values) {
130
12
    std::ostringstream out;
131
12
    out << "{";
132
12
    size_t idx = 0;
133
12
    for (const auto& [key, _] : partition_values) {
134
1
        if (idx++ > 0) {
135
0
            out << ", ";
136
0
        }
137
1
        out << key;
138
1
    }
139
12
    out << "}";
140
12
    return out.str();
141
12
}
142
143
241
const schema::external::TField* get_field_ptr(const schema::external::TFieldPtr& field_ptr) {
144
241
    if (!field_ptr.__isset.field_ptr || field_ptr.field_ptr == nullptr) {
145
0
        return nullptr;
146
0
    }
147
241
    return field_ptr.field_ptr.get();
148
241
}
149
150
const schema::external::TField* find_external_field_by_id(
151
0
        const schema::external::TStructField* root, int32_t field_id) {
152
0
    if (root == nullptr || !root->__isset.fields) {
153
0
        return nullptr;
154
0
    }
155
0
    for (const auto& field_ptr : root->fields) {
156
0
        const auto* field = get_field_ptr(field_ptr);
157
0
        if (field == nullptr) {
158
0
            continue;
159
0
        }
160
0
        if (field->__isset.id && field->id == field_id) {
161
0
            return field;
162
0
        }
163
0
        if (!field->__isset.nestedField) {
164
0
            continue;
165
0
        }
166
0
        if (field->nestedField.__isset.struct_field) {
167
0
            if (const auto* result =
168
0
                        find_external_field_by_id(&field->nestedField.struct_field, field_id);
169
0
                result != nullptr) {
170
0
                return result;
171
0
            }
172
0
        } else if (field->nestedField.__isset.array_field &&
173
0
                   field->nestedField.array_field.__isset.item_field) {
174
0
            const auto* child = get_field_ptr(field->nestedField.array_field.item_field);
175
0
            if (child != nullptr) {
176
0
                schema::external::TStructField child_root;
177
0
                child_root.__set_fields({field->nestedField.array_field.item_field});
178
0
                if (const auto* result = find_external_field_by_id(&child_root, field_id);
179
0
                    result != nullptr) {
180
0
                    return result;
181
0
                }
182
0
            }
183
0
        } else if (field->nestedField.__isset.map_field) {
184
0
            schema::external::TStructField child_root;
185
0
            std::vector<schema::external::TFieldPtr> children;
186
0
            if (field->nestedField.map_field.__isset.key_field) {
187
0
                children.push_back(field->nestedField.map_field.key_field);
188
0
            }
189
0
            if (field->nestedField.map_field.__isset.value_field) {
190
0
                children.push_back(field->nestedField.map_field.value_field);
191
0
            }
192
0
            child_root.__set_fields(children);
193
0
            if (const auto* result = find_external_field_by_id(&child_root, field_id);
194
0
                result != nullptr) {
195
0
                return result;
196
0
            }
197
0
        }
198
0
    }
199
0
    return nullptr;
200
0
}
201
202
bool find_external_field_path_by_id(const schema::external::TField* field, int32_t field_id,
203
49
                                    std::vector<const schema::external::TField*>* const path) {
204
49
    DORIS_CHECK(path != nullptr);
205
49
    DORIS_CHECK(field != nullptr);
206
49
    path->push_back(field);
207
49
    if (field->__isset.id && field->id == field_id) {
208
18
        return true;
209
18
    }
210
31
    if (field->__isset.nestedField && field->nestedField.__isset.struct_field &&
211
31
        field->nestedField.struct_field.__isset.fields) {
212
12
        for (const auto& child_ptr : field->nestedField.struct_field.fields) {
213
12
            const auto* child = get_field_ptr(child_ptr);
214
12
            if (child != nullptr && find_external_field_path_by_id(child, field_id, path)) {
215
8
                return true;
216
8
            }
217
12
        }
218
8
    }
219
23
    path->pop_back();
220
23
    return false;
221
31
}
222
223
std::optional<std::vector<const schema::external::TField*>> find_external_struct_field_path_by_id(
224
19
        const schema::external::TSchema& schema, int32_t field_id) {
225
19
    if (!schema.__isset.root_field || !schema.root_field.__isset.fields) {
226
0
        return std::nullopt;
227
0
    }
228
19
    std::vector<const schema::external::TField*> path;
229
37
    for (const auto& field_ptr : schema.root_field.fields) {
230
37
        const auto* field = get_field_ptr(field_ptr);
231
37
        if (field != nullptr && find_external_field_path_by_id(field, field_id, &path)) {
232
18
            return path;
233
18
        }
234
37
    }
235
1
    return std::nullopt;
236
19
}
237
238
bool find_column_identity_path_by_id(const std::vector<ColumnDefinition>& fields, int32_t field_id,
239
94
                                     std::vector<ColumnDefinition>* path) {
240
94
    DORIS_CHECK(path != nullptr);
241
94
    for (const auto& field : fields) {
242
89
        path->push_back(field);
243
89
        if (field.has_identifier_field_id() && field.get_identifier_field_id() == field_id) {
244
32
            return true;
245
32
        }
246
57
        if (find_column_identity_path_by_id(field.children, field_id, path)) {
247
18
            return true;
248
18
        }
249
39
        path->pop_back();
250
39
    }
251
44
    return false;
252
94
}
253
254
131
ColumnDefinition build_schema_identity_from_external_field(const schema::external::TField& field) {
255
131
    ColumnDefinition identity;
256
131
    if (field.__isset.id) {
257
131
        identity.identifier = Field::create_field<TYPE_INT>(field.id);
258
131
    }
259
131
    identity.name = field.__isset.name ? field.name : "";
260
131
    identity.name_mapping =
261
131
            field.__isset.name_mapping ? field.name_mapping : std::vector<std::string> {};
262
131
    identity.has_name_mapping =
263
131
            field.__isset.name_mapping_is_authoritative && field.name_mapping_is_authoritative;
264
131
    if (!field.__isset.nestedField) {
265
111
        return identity;
266
111
    }
267
20
    if (field.nestedField.__isset.struct_field && field.nestedField.struct_field.__isset.fields) {
268
26
        for (const auto& child_ptr : field.nestedField.struct_field.fields) {
269
26
            if (const auto* child = get_field_ptr(child_ptr); child != nullptr) {
270
26
                identity.children.push_back(build_schema_identity_from_external_field(*child));
271
26
            }
272
26
        }
273
20
    } else if (field.nestedField.__isset.array_field &&
274
0
               field.nestedField.array_field.__isset.item_field) {
275
0
        if (const auto* child = get_field_ptr(field.nestedField.array_field.item_field);
276
0
            child != nullptr) {
277
0
            identity.children.push_back(build_schema_identity_from_external_field(*child));
278
0
            identity.children.back().name = "element";
279
0
        }
280
0
    } else if (field.nestedField.__isset.map_field) {
281
0
        if (field.nestedField.map_field.__isset.key_field) {
282
0
            if (const auto* child = get_field_ptr(field.nestedField.map_field.key_field);
283
0
                child != nullptr) {
284
0
                identity.children.push_back(build_schema_identity_from_external_field(*child));
285
0
                identity.children.back().name = "key";
286
0
            }
287
0
        }
288
0
        if (field.nestedField.map_field.__isset.value_field) {
289
0
            if (const auto* child = get_field_ptr(field.nestedField.map_field.value_field);
290
0
                child != nullptr) {
291
0
                identity.children.push_back(build_schema_identity_from_external_field(*child));
292
0
                identity.children.back().name = "value";
293
0
            }
294
0
        }
295
0
    }
296
20
    return identity;
297
131
}
298
299
const ColumnDefinition* find_identity_child(const ColumnDefinition& projected_child,
300
2
                                            const ColumnDefinition& identity_parent) {
301
2
    const auto child_it = std::ranges::find_if(
302
3
            identity_parent.children, [&](const ColumnDefinition& identity_child) {
303
3
                if (projected_child.has_identifier_field_id() &&
304
3
                    identity_child.has_identifier_field_id()) {
305
3
                    return projected_child.get_identifier_field_id() ==
306
3
                           identity_child.get_identifier_field_id();
307
3
                }
308
0
                if (to_lower(projected_child.name) == to_lower(identity_child.name)) {
309
0
                    return true;
310
0
                }
311
0
                return std::ranges::any_of(
312
0
                        identity_child.name_mapping, [&](const std::string& alias) {
313
0
                            return to_lower(projected_child.name) == to_lower(alias);
314
0
                        });
315
0
            });
316
2
    return child_it == identity_parent.children.end() ? nullptr : &*child_it;
317
2
}
318
319
38
void attach_full_schema_identity(ColumnDefinition* projected, const ColumnDefinition& identity) {
320
38
    DORIS_CHECK(projected != nullptr);
321
    // Access-path children control materialization, but wrapper discovery needs sibling IDs that
322
    // were pruned from that projection. Keep the complete identity tree on a separate channel.
323
38
    projected->identity_children = identity.children;
324
38
    for (auto& projected_child : projected->children) {
325
2
        if (const auto* identity_child = find_identity_child(projected_child, identity);
326
2
            identity_child != nullptr) {
327
2
            attach_full_schema_identity(&projected_child, *identity_child);
328
2
        }
329
2
    }
330
38
}
331
332
13
void clear_initial_default_metadata(ColumnDefinition* column) {
333
13
    DORIS_CHECK(column != nullptr);
334
13
    column->initial_default_value.reset();
335
13
    column->initial_default_value_is_base64 = false;
336
13
    for (auto& child : column->children) {
337
6
        clear_initial_default_metadata(&child);
338
6
    }
339
13
}
340
341
15
bool external_field_matches_name(const schema::external::TField& field, const std::string& name) {
342
15
    if (field.__isset.name && to_lower(field.name) == to_lower(name)) {
343
5
        return true;
344
5
    }
345
10
    return field.__isset.name_mapping &&
346
10
           std::ranges::any_of(field.name_mapping, [&](const std::string& alias) {
347
8
               return to_lower(alias) == to_lower(name);
348
8
           });
349
15
}
350
351
DataTypePtr find_struct_child_type_by_external_field(const DataTypeStruct& struct_type,
352
                                                     const schema::external::TField& field,
353
18
                                                     bool prefer_current_name) {
354
18
    if (prefer_current_name && field.__isset.name) {
355
22
        for (size_t field_idx = 0; field_idx < struct_type.get_elements().size(); ++field_idx) {
356
18
            if (to_lower(field.name) == to_lower(struct_type.get_element_name(field_idx))) {
357
11
                return struct_type.get_element(field_idx);
358
11
            }
359
18
        }
360
15
    }
361
10
    for (size_t field_idx = 0; field_idx < struct_type.get_elements().size(); ++field_idx) {
362
8
        const auto& element_name = struct_type.get_element_name(field_idx);
363
8
        if (external_field_matches_name(field, element_name)) {
364
5
            return struct_type.get_element(field_idx);
365
5
        }
366
8
    }
367
2
    return nullptr;
368
7
}
369
370
DataTypePtr restore_current_primitive_type(const schema::external::TField& field,
371
75
                                           DataTypePtr fallback_type) {
372
75
    if (!field.__isset.type) {
373
44
        return fallback_type;
374
44
    }
375
31
    DORIS_CHECK(fallback_type != nullptr);
376
31
    const auto primitive_type = thrift_to_type(field.type.type);
377
31
    if (is_complex_type(primitive_type)) {
378
2
        return fallback_type;
379
2
    }
380
    // The delete file can expose an older physical type, but initial defaults belong to the
381
    // current table field. Restore that type from FE before parsing the default and let the table
382
    // reader apply the normal promotion cast to the delete-key type.
383
29
    return DataTypeFactory::instance().create_data_type(
384
29
            primitive_type, fallback_type->is_nullable(),
385
29
            field.type.__isset.precision ? field.type.precision : 0,
386
29
            field.type.__isset.scale ? field.type.scale : 0,
387
29
            field.type.__isset.len ? field.type.len : -1);
388
31
}
389
390
ColumnDefinition build_schema_column_metadata_from_external_field(
391
75
        const schema::external::TField& field, DataTypePtr type) {
392
75
    type = restore_current_primitive_type(field, std::move(type));
393
75
    return ColumnDefinition {
394
75
            .identifier = field.__isset.id ? Field::create_field<TYPE_INT>(field.id) : Field {},
395
75
            .name = field.__isset.name ? field.name : "",
396
75
            .name_mapping =
397
75
                    field.__isset.name_mapping ? field.name_mapping : std::vector<std::string> {},
398
75
            .has_name_mapping = field.__isset.name_mapping_is_authoritative &&
399
75
                                field.name_mapping_is_authoritative,
400
75
            .type = std::move(type),
401
75
            .children = {},
402
75
            .default_expr = nullptr,
403
75
            .initial_default_value = field.__isset.initial_default_value
404
75
                                             ? std::make_optional(field.initial_default_value)
405
75
                                             : std::nullopt,
406
75
            .initial_default_value_is_base64 = field.__isset.initial_default_value_is_base64 &&
407
75
                                               field.initial_default_value_is_base64,
408
75
            .is_optional = field.__isset.is_optional ? std::make_optional(field.is_optional)
409
75
                                                     : std::nullopt,
410
75
            .is_partition_key = false,
411
75
    };
412
75
}
413
414
// NOLINTNEXTLINE(readability-function-size): keep recursive Iceberg type reconstruction together.
415
ColumnDefinition build_schema_column_from_external_field(const schema::external::TField& field,
416
                                                         DataTypePtr type,
417
49
                                                         bool prefer_current_name) {
418
49
    auto column = build_schema_column_metadata_from_external_field(field, std::move(type));
419
49
    if (column.type == nullptr || !field.__isset.nestedField) {
420
33
        return column;
421
33
    }
422
423
16
    const auto nested_type = remove_nullable(column.type);
424
16
    switch (nested_type->get_primitive_type()) {
425
10
    case TYPE_STRUCT: {
426
10
        if (!field.nestedField.__isset.struct_field ||
427
10
            !field.nestedField.struct_field.__isset.fields) {
428
0
            return column;
429
0
        }
430
10
        const auto& struct_type = assert_cast<const DataTypeStruct&>(*nested_type);
431
18
        for (const auto& child_ptr : field.nestedField.struct_field.fields) {
432
18
            const auto* child_field = get_field_ptr(child_ptr);
433
18
            if (child_field == nullptr || !child_field->__isset.name) {
434
0
                continue;
435
0
            }
436
18
            auto child_type = find_struct_child_type_by_external_field(struct_type, *child_field,
437
18
                                                                       prefer_current_name);
438
18
            if (child_type == nullptr) {
439
2
                continue;
440
2
            }
441
16
            column.children.push_back(build_schema_column_from_external_field(
442
16
                    *child_field, child_type, prefer_current_name));
443
16
        }
444
10
        break;
445
10
    }
446
3
    case TYPE_ARRAY: {
447
3
        if (!field.nestedField.__isset.array_field ||
448
3
            !field.nestedField.array_field.__isset.item_field) {
449
0
            return column;
450
0
        }
451
3
        const auto* item_field = get_field_ptr(field.nestedField.array_field.item_field);
452
3
        if (item_field == nullptr) {
453
0
            return column;
454
0
        }
455
3
        const auto& array_type = assert_cast<const DataTypeArray&>(*nested_type);
456
3
        auto child = build_schema_column_from_external_field(
457
3
                *item_field, array_type.get_nested_type(), prefer_current_name);
458
3
        child.name = "element";
459
3
        if (child.has_identifier_name()) {
460
0
            child.identifier = Field::create_field<TYPE_STRING>(child.name);
461
0
        }
462
3
        column.children.push_back(std::move(child));
463
3
        break;
464
3
    }
465
3
    case TYPE_MAP: {
466
3
        if (!field.nestedField.__isset.map_field ||
467
3
            !field.nestedField.map_field.__isset.key_field ||
468
3
            !field.nestedField.map_field.__isset.value_field) {
469
0
            return column;
470
0
        }
471
3
        const auto& map_type = assert_cast<const DataTypeMap&>(*nested_type);
472
3
        const auto* key_field = get_field_ptr(field.nestedField.map_field.key_field);
473
3
        if (key_field != nullptr) {
474
3
            auto child = build_schema_column_from_external_field(
475
3
                    *key_field, map_type.get_key_type(), prefer_current_name);
476
3
            child.name = "key";
477
3
            if (child.has_identifier_name()) {
478
0
                child.identifier = Field::create_field<TYPE_STRING>(child.name);
479
0
            }
480
3
            column.children.push_back(std::move(child));
481
3
        }
482
3
        const auto* value_field = get_field_ptr(field.nestedField.map_field.value_field);
483
3
        if (value_field != nullptr) {
484
3
            auto child = build_schema_column_from_external_field(
485
3
                    *value_field, map_type.get_value_type(), prefer_current_name);
486
3
            child.name = "value";
487
3
            if (child.has_identifier_name()) {
488
0
                child.identifier = Field::create_field<TYPE_STRING>(child.name);
489
0
            }
490
3
            column.children.push_back(std::move(child));
491
3
        }
492
3
        break;
493
3
    }
494
0
    default:
495
0
        break;
496
16
    }
497
16
    return column;
498
16
}
499
500
const schema::external::TField* find_external_root_field(const TFileScanRangeParams* params,
501
107
                                                         const ColumnDefinition& column) {
502
107
    if (params == nullptr || !params->__isset.history_schema_info ||
503
107
        params->history_schema_info.empty()) {
504
46
        return nullptr;
505
46
    }
506
61
    const auto* schema = &params->history_schema_info.front();
507
61
    if (params->__isset.current_schema_id) {
508
62
        for (const auto& candidate_schema : params->history_schema_info) {
509
62
            if (candidate_schema.__isset.schema_id &&
510
62
                candidate_schema.schema_id == params->current_schema_id) {
511
61
                schema = &candidate_schema;
512
61
                break;
513
61
            }
514
62
        }
515
61
    }
516
61
    if (!schema->__isset.root_field || !schema->root_field.__isset.fields) {
517
0
        return nullptr;
518
0
    }
519
61
    if (!supports_iceberg_scan_semantics_v1(params)) {
520
        // Old BEs used one ordered current-name/alias pass. Preserve that result for old-FE plans
521
        // until the explicit scan-semantics marker makes exact-name precedence cluster-wide.
522
7
        for (const auto& field_ptr : schema->root_field.fields) {
523
7
            const auto* field = get_field_ptr(field_ptr);
524
7
            if (field != nullptr && external_field_matches_name(*field, column.name)) {
525
7
                return field;
526
7
            }
527
7
        }
528
0
        return nullptr;
529
7
    }
530
    // A reused name identifies the newly added field, not an older sibling that retained that
531
    // spelling as an alias. Exhaust exact current names before consulting historical aliases.
532
62
    for (const auto& field_ptr : schema->root_field.fields) {
533
62
        const auto* field = get_field_ptr(field_ptr);
534
62
        if (field != nullptr && field->__isset.name &&
535
62
            to_lower(field->name) == to_lower(column.name)) {
536
53
            return field;
537
53
        }
538
62
    }
539
1
    for (const auto& field_ptr : schema->root_field.fields) {
540
1
        const auto* field = get_field_ptr(field_ptr);
541
1
        if (field != nullptr && field->__isset.name_mapping &&
542
1
            std::ranges::any_of(field->name_mapping, [&](const std::string& alias) {
543
0
                return to_lower(alias) == to_lower(column.name);
544
0
            })) {
545
0
            return field;
546
0
        }
547
1
    }
548
1
    return nullptr;
549
1
}
550
551
2
std::string expr_context_debug_string(const VExprContextSPtr& context) {
552
2
    if (context == nullptr) {
553
0
        return "null";
554
0
    }
555
2
    const auto root = context->root();
556
2
    if (root == nullptr) {
557
0
        return "VExprContext{root=null}";
558
0
    }
559
2
    std::ostringstream out;
560
2
    out << "VExprContext{root_name=" << root->expr_name() << ", root_debug=" << root->debug_string()
561
2
        << "}";
562
2
    return out.str();
563
2
}
564
565
1
std::string table_filter_debug_string(const TableFilter& filter) {
566
1
    std::ostringstream out;
567
1
    out << "TableFilter{conjunct=" << expr_context_debug_string(filter.conjunct)
568
1
        << ", global_indices="
569
1
        << join_table_reader_debug_strings(
570
1
                   filter.global_indices,
571
1
                   [](GlobalIndex global_index) { return std::to_string(global_index.value()); })
572
1
        << "}";
573
1
    return out.str();
574
1
}
575
576
4
bool contains_runtime_filter(const VExprContextSPtrs& conjuncts) {
577
4
    return std::ranges::any_of(conjuncts, [](const auto& conjunct) {
578
4
        return conjunct != nullptr && conjunct->root() != nullptr &&
579
4
               conjunct->root()->is_rf_wrapper();
580
4
    });
581
4
}
582
583
126
void collect_global_indices(const VExprSPtr& expr, std::set<GlobalIndex>* global_indices) {
584
126
    if (expr == nullptr) {
585
0
        return;
586
0
    }
587
126
    if (expr->is_rf_wrapper()) {
588
        // RuntimeFilterExpr wraps a real predicate expression but its own thrift node can still
589
        // look like SLOT_REF. Collect indices from the wrapped predicate; do not cast the wrapper
590
        // itself to VSlotRef.
591
10
        collect_global_indices(expr->get_impl(), global_indices);
592
10
        return;
593
10
    }
594
116
    if (expr->is_slot_ref()) {
595
39
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
596
39
        DORIS_CHECK(slot_ref->column_id() >= 0);
597
39
        global_indices->insert(GlobalIndex(cast_set<size_t>(slot_ref->column_id())));
598
39
    }
599
116
    for (const auto& child : expr->children()) {
600
76
        collect_global_indices(child, global_indices);
601
76
    }
602
116
}
603
604
Status build_table_filters_from_conjunct(const VExprContextSPtr& conjunct, RuntimeState* state,
605
38
                                         std::vector<TableFilter>* table_filters) {
606
38
    if (conjunct == nullptr) {
607
0
        return Status::OK();
608
0
    }
609
38
    std::set<GlobalIndex> global_indices;
610
38
    collect_global_indices(conjunct->root(), &global_indices);
611
38
    if (!global_indices.empty()) {
612
36
        TableFilter table_filter;
613
36
        VExprSPtr filter_root;
614
36
        RETURN_IF_ERROR(clone_table_expr_tree(conjunct->root(), &filter_root));
615
36
        table_filter.conjunct = VExprContext::create_shared(std::move(filter_root));
616
37
        for (const auto global_index : global_indices) {
617
37
            table_filter.global_indices.push_back(global_index);
618
37
        }
619
36
        table_filters->push_back(std::move(table_filter));
620
36
    }
621
38
    return Status::OK();
622
38
}
623
624
Status parse_deletion_vector(const char* buf, size_t buffer_size, DeleteFileDesc::Format format,
625
5
                             DeletionVector* deletion_vector) {
626
5
    DORIS_CHECK(buf != nullptr);
627
5
    DORIS_CHECK(deletion_vector != nullptr);
628
5
    DORIS_CHECK(format == DeleteFileDesc::Format::PAIMON ||
629
5
                format == DeleteFileDesc::Format::ICEBERG);
630
631
5
    if (format == DeleteFileDesc::Format::PAIMON) {
632
1
        RETURN_IF_ERROR(decode_paimon_deletion_vector_buffer(buf, buffer_size, deletion_vector));
633
1
        return Status::OK();
634
1
    }
635
636
4
    return decode_iceberg_deletion_vector_buffer(buf, buffer_size, deletion_vector);
637
5
}
638
639
} // namespace
640
641
std::shared_ptr<io::FileSystemProperties> create_system_properties(
642
223
        const TFileScanRangeParams* scan_params) {
643
223
    auto system_properties = std::make_shared<io::FileSystemProperties>();
644
223
    if (scan_params == nullptr || !scan_params->__isset.file_type) {
645
139
        system_properties->system_type = TFileType::FILE_LOCAL;
646
139
        return system_properties;
647
139
    }
648
84
    system_properties->system_type = scan_params->file_type;
649
84
    system_properties->properties = scan_params->properties;
650
84
    system_properties->hdfs_params = scan_params->hdfs_params;
651
84
    if (scan_params->__isset.broker_addresses) {
652
0
        system_properties->broker_addresses.assign(scan_params->broker_addresses.begin(),
653
0
                                                   scan_params->broker_addresses.end());
654
0
    }
655
84
    return system_properties;
656
223
}
657
658
12
std::string TableReader::debug_string() const {
659
12
    std::ostringstream out;
660
12
    out << "TableReader{format=" << file_format_to_string(_format)
661
12
        << ", push_down_agg_type=" << push_down_agg_to_string(_push_down_agg_type)
662
12
        << ", aggregate_pushdown_tried=" << _aggregate_pushdown_tried
663
12
        << ", has_current_reader=" << (_data_reader.reader != nullptr)
664
12
        << ", has_current_task=" << (_current_task != nullptr)
665
12
        << ", current_file=" << current_file_debug_string(_current_task)
666
12
        << ", has_delete_rows=" << (_delete_rows != nullptr)
667
12
        << ", delete_row_count=" << (_delete_rows == nullptr ? 0 : _delete_rows->size())
668
12
        << ", has_deletion_vector=" << (_deletion_vector != nullptr)
669
12
        << ", deletion_vector_cardinality="
670
12
        << (_deletion_vector == nullptr ? 0 : _deletion_vector->cardinality())
671
12
        << ", has_system_properties=" << (_system_properties != nullptr) << ", system_type="
672
12
        << (_system_properties == nullptr ? static_cast<int>(TFileType::FILE_LOCAL)
673
12
                                          : static_cast<int>(_system_properties->system_type))
674
12
        << ", has_scan_params=" << (_scan_params != nullptr)
675
12
        << ", has_io_ctx=" << (_io_ctx != nullptr)
676
12
        << ", has_runtime_state=" << (_runtime_state != nullptr)
677
12
        << ", has_scanner_profile=" << (_scanner_profile != nullptr)
678
12
        << ", mapper_options=" << _mapper_options.debug_string() << ", projected_columns="
679
12
        << join_table_reader_debug_strings(
680
12
                   _projected_columns,
681
12
                   [](const ColumnDefinition& column) { return column.debug_string(); })
682
12
        << ", partition_values=" << partition_values_debug_string(_partition_values)
683
12
        << ", table_filters="
684
12
        << join_table_reader_debug_strings(
685
12
                   _table_filters,
686
12
                   [](const TableFilter& filter) { return table_filter_debug_string(filter); })
687
12
        << ", conjunct_count=" << _conjuncts.size() << ", conjuncts="
688
12
        << join_table_reader_debug_strings(_conjuncts,
689
12
                                           [](const VExprContextSPtr& conjunct) {
690
1
                                               return expr_context_debug_string(conjunct);
691
1
                                           })
692
12
        << ", file_schema="
693
12
        << join_table_reader_debug_strings(
694
12
                   _data_reader.file_schema,
695
12
                   [](const ColumnDefinition& field) { return field.debug_string(); })
696
12
        << ", file_block_layout="
697
12
        << join_table_reader_debug_strings(
698
12
                   _data_reader.file_block_layout,
699
12
                   [](const FileBlockColumn& column) {
700
2
                       std::ostringstream column_out;
701
2
                       column_out << "FileBlockColumn{file_column_id=" << column.file_column_id
702
2
                                  << ", name=" << column.name << ", type="
703
2
                                  << (column.type == nullptr ? "null" : column.type->get_name())
704
2
                                  << "}";
705
2
                       return column_out.str();
706
2
                   })
707
12
        << ", block_template_columns=" << _data_reader.block_template.columns()
708
12
        << ", column_mapper="
709
12
        << (_data_reader.column_mapper == nullptr ? "null"
710
12
                                                  : _data_reader.column_mapper->debug_string())
711
12
        << "}";
712
12
    return out.str();
713
12
}
714
715
Status TableReader::annotate_projected_column(const TFileScanSlotInfo& slot_info,
716
                                              ProjectedColumnBuildContext* context,
717
31
                                              ColumnDefinition* column) const {
718
31
    (void)slot_info;
719
31
    DORIS_CHECK(context != nullptr);
720
31
    DORIS_CHECK(column != nullptr);
721
31
    context->schema_column.reset();
722
31
    const auto* schema_field = find_external_root_field(context->scan_params, *column);
723
31
    if (schema_field == nullptr) {
724
7
        return Status::OK();
725
7
    }
726
24
    const bool use_current_semantics = supports_iceberg_scan_semantics_v1(context->scan_params);
727
24
    context->schema_column = build_schema_column_from_external_field(*schema_field, column->type,
728
24
                                                                     use_current_semantics);
729
24
    if (!use_current_semantics) {
730
        // IDs and encoded defaults predate the result-changing semantics. Strip only the new
731
        // default channel so an old-FE plan keeps the same generic root/nested values on every BE.
732
7
        clear_initial_default_metadata(&*context->schema_column);
733
7
    }
734
24
    column->identifier = context->schema_column->identifier;
735
24
    column->name_mapping = context->schema_column->name_mapping;
736
24
    column->has_name_mapping = context->schema_column->has_name_mapping;
737
    // Projected roots already carry a generic FE default expression, but Iceberg binary defaults
738
    // need the raw Base64 marker so missing-file materialization can decode rather than copy text.
739
24
    column->initial_default_value = context->schema_column->initial_default_value;
740
24
    column->initial_default_value_is_base64 =
741
24
            context->schema_column->initial_default_value_is_base64;
742
24
    return Status::OK();
743
31
}
744
745
std::optional<ColumnDefinition> TableReader::_find_table_column_by_field_id(
746
1
        int32_t field_id, DataTypePtr type, bool include_historical_schemas) const {
747
1
    if (_scan_params == nullptr || !_scan_params->__isset.history_schema_info ||
748
1
        _scan_params->history_schema_info.empty()) {
749
1
        return std::nullopt;
750
1
    }
751
0
    const auto find_field = [field_id](const schema::external::TSchema& schema) {
752
0
        return schema.__isset.root_field ? find_external_field_by_id(&schema.root_field, field_id)
753
0
                                         : nullptr;
754
0
    };
755
756
0
    const auto* current_schema = &_scan_params->history_schema_info.front();
757
0
    if (_scan_params->__isset.current_schema_id) {
758
0
        for (const auto& candidate_schema : _scan_params->history_schema_info) {
759
0
            if (candidate_schema.__isset.schema_id &&
760
0
                candidate_schema.schema_id == _scan_params->current_schema_id) {
761
0
                current_schema = &candidate_schema;
762
0
                break;
763
0
            }
764
0
        }
765
0
    }
766
0
    if (const auto* field = find_field(*current_schema); field != nullptr) {
767
0
        return build_schema_column_from_external_field(
768
0
                *field, std::move(type), supports_iceberg_scan_semantics_v1(_scan_params));
769
0
    }
770
0
    if (!include_historical_schemas) {
771
0
        return std::nullopt;
772
0
    }
773
774
0
    const schema::external::TSchema* latest_schema = nullptr;
775
0
    const schema::external::TField* latest_field = nullptr;
776
0
    for (const auto& candidate_schema : _scan_params->history_schema_info) {
777
0
        if (&candidate_schema == current_schema) {
778
0
            continue;
779
0
        }
780
0
        const auto* candidate_field = find_field(candidate_schema);
781
0
        if (candidate_field == nullptr) {
782
0
            continue;
783
0
        }
784
0
        if (latest_schema == nullptr || (candidate_schema.__isset.schema_id &&
785
0
                                         (!latest_schema->__isset.schema_id ||
786
0
                                          candidate_schema.schema_id > latest_schema->schema_id))) {
787
0
            latest_schema = &candidate_schema;
788
0
            latest_field = candidate_field;
789
0
        }
790
0
    }
791
0
    if (latest_field == nullptr) {
792
0
        return std::nullopt;
793
0
    }
794
0
    return build_schema_column_from_external_field(
795
0
            *latest_field, std::move(type), supports_iceberg_scan_semantics_v1(_scan_params));
796
0
}
797
798
std::optional<std::vector<ColumnDefinition>> TableReader::_find_table_column_path_by_field_id(
799
19
        int32_t field_id, DataTypePtr leaf_type, bool include_historical_schemas) const {
800
19
    if (_scan_params == nullptr || !_scan_params->__isset.history_schema_info ||
801
19
        _scan_params->history_schema_info.empty()) {
802
1
        return std::nullopt;
803
1
    }
804
18
    const auto build_path = [&](const schema::external::TSchema& schema)
805
19
            -> std::optional<std::vector<ColumnDefinition>> {
806
19
        auto external_path = find_external_struct_field_path_by_id(schema, field_id);
807
19
        if (!external_path.has_value()) {
808
1
            return std::nullopt;
809
1
        }
810
811
18
        std::vector<DataTypePtr> path_types(external_path->size());
812
18
        path_types.back() = leaf_type;
813
26
        for (size_t index = external_path->size(); index > 1; --index) {
814
8
            const auto* parent = (*external_path)[index - 2];
815
8
            const auto* child = (*external_path)[index - 1];
816
8
            DORIS_CHECK(parent != nullptr);
817
8
            DORIS_CHECK(child != nullptr);
818
8
            DORIS_CHECK(child->__isset.name);
819
8
            if (!parent->__isset.nestedField || !parent->nestedField.__isset.struct_field) {
820
0
                return std::nullopt;
821
0
            }
822
8
            DataTypePtr path_type = std::make_shared<DataTypeStruct>(
823
8
                    DataTypes {path_types[index - 1]}, Strings {child->name});
824
8
            if (parent->__isset.is_optional && parent->is_optional) {
825
8
                path_type = make_nullable(path_type);
826
8
            }
827
8
            path_types[index - 2] = std::move(path_type);
828
8
        }
829
830
18
        std::vector<ColumnDefinition> result;
831
18
        result.reserve(external_path->size());
832
44
        for (size_t index = 0; index < external_path->size(); ++index) {
833
26
            result.push_back(build_schema_column_metadata_from_external_field(
834
26
                    *(*external_path)[index], path_types[index]));
835
26
        }
836
        // Keep metadata hierarchy aligned with the synthetic exact-ID ancestor types.
837
26
        for (size_t index = result.size(); index > 1; --index) {
838
8
            result[index - 2].children.push_back(result[index - 1]);
839
8
        }
840
18
        return result;
841
18
    };
842
843
18
    const auto* current_schema = &_scan_params->history_schema_info.front();
844
18
    if (_scan_params->__isset.current_schema_id) {
845
18
        for (const auto& candidate_schema : _scan_params->history_schema_info) {
846
18
            if (candidate_schema.__isset.schema_id &&
847
18
                candidate_schema.schema_id == _scan_params->current_schema_id) {
848
18
                current_schema = &candidate_schema;
849
18
                break;
850
18
            }
851
18
        }
852
18
    }
853
18
    if (auto path = build_path(*current_schema); path.has_value()) {
854
17
        return path;
855
17
    }
856
1
    if (!include_historical_schemas) {
857
0
        return std::nullopt;
858
0
    }
859
860
1
    const schema::external::TSchema* latest_schema = nullptr;
861
1
    std::optional<std::vector<ColumnDefinition>> latest_path;
862
2
    for (const auto& candidate_schema : _scan_params->history_schema_info) {
863
2
        if (&candidate_schema == current_schema) {
864
1
            continue;
865
1
        }
866
1
        auto candidate_path = build_path(candidate_schema);
867
1
        if (!candidate_path.has_value()) {
868
0
            continue;
869
0
        }
870
1
        if (latest_schema == nullptr || (candidate_schema.__isset.schema_id &&
871
0
                                         (!latest_schema->__isset.schema_id ||
872
1
                                          candidate_schema.schema_id > latest_schema->schema_id))) {
873
1
            latest_schema = &candidate_schema;
874
1
            latest_path = std::move(candidate_path);
875
1
        }
876
1
    }
877
1
    return latest_path;
878
1
}
879
880
std::optional<std::vector<ColumnDefinition>>
881
TableReader::_find_table_column_identity_path_by_field_id(int32_t field_id,
882
41
                                                          bool include_historical_schemas) const {
883
41
    if (_scan_params == nullptr || !_scan_params->__isset.history_schema_info ||
884
41
        _scan_params->history_schema_info.empty()) {
885
9
        return std::nullopt;
886
9
    }
887
32
    const auto find_path = [field_id](const schema::external::TSchema& schema)
888
37
            -> std::optional<std::vector<ColumnDefinition>> {
889
37
        if (!schema.__isset.root_field || !schema.root_field.__isset.fields) {
890
0
            return std::nullopt;
891
0
        }
892
37
        std::vector<ColumnDefinition> roots;
893
37
        roots.reserve(schema.root_field.fields.size());
894
69
        for (const auto& field_ptr : schema.root_field.fields) {
895
69
            const auto* field = get_field_ptr(field_ptr);
896
69
            if (field != nullptr) {
897
69
                roots.push_back(build_schema_identity_from_external_field(*field));
898
69
            }
899
69
        }
900
37
        std::vector<ColumnDefinition> path;
901
37
        if (find_column_identity_path_by_id(roots, field_id, &path)) {
902
32
            return path;
903
32
        }
904
5
        return std::nullopt;
905
37
    };
906
907
32
    const auto* current_schema = &_scan_params->history_schema_info.front();
908
32
    if (_scan_params->__isset.current_schema_id) {
909
32
        for (const auto& candidate_schema : _scan_params->history_schema_info) {
910
32
            if (candidate_schema.__isset.schema_id &&
911
32
                candidate_schema.schema_id == _scan_params->current_schema_id) {
912
32
                current_schema = &candidate_schema;
913
32
                break;
914
32
            }
915
32
        }
916
32
    }
917
32
    if (auto path = find_path(*current_schema); path.has_value()) {
918
27
        return path;
919
27
    }
920
5
    if (!include_historical_schemas) {
921
0
        return std::nullopt;
922
0
    }
923
924
5
    const schema::external::TSchema* latest_schema = nullptr;
925
5
    std::optional<std::vector<ColumnDefinition>> latest_path;
926
10
    for (const auto& candidate_schema : _scan_params->history_schema_info) {
927
10
        if (&candidate_schema == current_schema) {
928
5
            continue;
929
5
        }
930
5
        auto candidate_path = find_path(candidate_schema);
931
5
        if (!candidate_path.has_value()) {
932
0
            continue;
933
0
        }
934
5
        if (latest_schema == nullptr || (candidate_schema.__isset.schema_id &&
935
0
                                         (!latest_schema->__isset.schema_id ||
936
5
                                          candidate_schema.schema_id > latest_schema->schema_id))) {
937
5
            latest_schema = &candidate_schema;
938
5
            latest_path = std::move(candidate_path);
939
5
        }
940
5
    }
941
5
    return latest_path;
942
5
}
943
944
223
Status TableReader::init(TableReadOptions&& options) {
945
223
    _scanner_profile = options.scanner_profile;
946
223
    if (_scanner_profile != nullptr) {
947
94
        const auto hierarchy = file_scan_profile::ensure_hierarchy(_scanner_profile);
948
94
        static const char* table_profile = file_scan_profile::TABLE_READER;
949
94
        static const char* file_reader_profile = file_scan_profile::FILE_READER;
950
94
        _profile.total_timer = hierarchy.table_reader;
951
94
        _profile.file_reader_total_timer = hierarchy.file_reader;
952
94
        _profile.init_timer =
953
94
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "InitTime", table_profile, 1);
954
94
        _profile.num_delete_files = ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "NumDeleteFiles",
955
94
                                                                 TUnit::UNIT, table_profile, 1);
956
94
        _profile.num_delete_rows = ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "NumDeleteRows",
957
94
                                                                TUnit::UNIT, table_profile, 1);
958
94
        _profile.parse_delete_file_time = ADD_CHILD_TIMER_WITH_LEVEL(
959
94
                _scanner_profile, "ParseDeleteFileTime", table_profile, 1);
960
94
        _profile.decoded_dv_cache_hit_count =
961
94
                ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "DeletionVectorDecodedCacheHitCount",
962
94
                                             TUnit::UNIT, table_profile, 1);
963
94
        _profile.decoded_dv_cache_miss_count = ADD_CHILD_COUNTER_WITH_LEVEL(
964
94
                _scanner_profile, "DeletionVectorDecodedCacheMissCount", TUnit::UNIT, table_profile,
965
94
                1);
966
94
        _profile.dv_file_cache_hit_count = ADD_CHILD_COUNTER_WITH_LEVEL(
967
94
                _scanner_profile, "DeletionVectorFileCacheHitCount", TUnit::UNIT, table_profile, 1);
968
94
        _profile.dv_file_cache_miss_count =
969
94
                ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "DeletionVectorFileCacheMissCount",
970
94
                                             TUnit::UNIT, table_profile, 1);
971
94
        _profile.dv_file_cache_peer_read_count = ADD_CHILD_COUNTER_WITH_LEVEL(
972
94
                _scanner_profile, "DeletionVectorFileCachePeerReadCount", TUnit::UNIT,
973
94
                table_profile, 1);
974
94
        _profile.exec_timer =
975
94
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "GetBlockTime", table_profile, 1);
976
94
        _profile.prepare_split_timer =
977
94
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "PrepareSplitTime", table_profile, 1);
978
94
        _profile.finalize_timer =
979
94
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "FinalizeBlockTime", table_profile, 1);
980
94
        _profile.create_reader_timer =
981
94
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "CreateReaderTime", table_profile, 1);
982
94
        _profile.pushdown_agg_timer =
983
94
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "PushDownAggTime", table_profile, 1);
984
94
        _profile.open_reader_timer =
985
94
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "OpenReaderTime", table_profile, 1);
986
94
        _profile.refresh_conjuncts_timer = ADD_CHILD_TIMER_WITH_LEVEL(
987
94
                _scanner_profile, "RefreshConjunctsTime", table_profile, 1);
988
94
        _profile.runtime_filter_partition_prune_timer = ADD_CHILD_TIMER_WITH_LEVEL(
989
94
                _scanner_profile, "FileScannerRuntimeFilterPartitionPruningTime", table_profile, 1);
990
94
        _profile.runtime_filter_partition_pruned_range_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
991
94
                _scanner_profile, "RuntimeFilterPartitionPrunedRangeNum", TUnit::UNIT,
992
94
                table_profile, 1);
993
94
        _profile.close_timer =
994
94
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "CloseTime", table_profile, 1);
995
        // Lifecycle timer names remain globally unique because RuntimeProfile's visual hierarchy
996
        // does not namespace counters that share the same display parent.
997
94
        _profile.file_reader_init_timer = ADD_CHILD_TIMER_WITH_LEVEL(
998
94
                _scanner_profile, "FileReaderInitTime", file_reader_profile, 1);
999
94
        _profile.file_reader_schema_timer = ADD_CHILD_TIMER_WITH_LEVEL(
1000
94
                _scanner_profile, "FileReaderGetSchemaTime", file_reader_profile, 1);
1001
94
        _profile.file_reader_mapper_timer = ADD_CHILD_TIMER_WITH_LEVEL(
1002
94
                _scanner_profile, "FileReaderCreateColumnMapperTime", file_reader_profile, 1);
1003
94
        _profile.file_reader_open_timer = ADD_CHILD_TIMER_WITH_LEVEL(
1004
94
                _scanner_profile, "FileReaderOpenTime", file_reader_profile, 1);
1005
94
        _profile.file_reader_refresh_timer = ADD_CHILD_TIMER_WITH_LEVEL(
1006
94
                _scanner_profile, "FileReaderRefreshScanRequestTime", file_reader_profile, 1);
1007
94
        _profile.file_reader_get_block_timer = ADD_CHILD_TIMER_WITH_LEVEL(
1008
94
                _scanner_profile, "FileReaderGetBlockTime", file_reader_profile, 1);
1009
94
        _profile.file_reader_aggregate_timer = ADD_CHILD_TIMER_WITH_LEVEL(
1010
94
                _scanner_profile, "FileReaderAggregatePushDownTime", file_reader_profile, 1);
1011
94
        _profile.file_reader_close_timer = ADD_CHILD_TIMER_WITH_LEVEL(
1012
94
                _scanner_profile, "FileReaderCloseTime", file_reader_profile, 1);
1013
94
    }
1014
    // Establish lifecycle timers before consuming options or constructing filesystem properties;
1015
    // placing these scopes at the tail records only scope teardown and hides expensive init work.
1016
223
    SCOPED_TIMER(_profile.total_timer);
1017
223
    SCOPED_TIMER(_profile.init_timer);
1018
223
    _scan_params = options.scan_params;
1019
223
    _format = options.format;
1020
223
    _io_ctx = options.io_ctx;
1021
223
    _runtime_state = options.runtime_state;
1022
223
    _file_slot_descs = options.file_slot_descs;
1023
223
    _push_down_agg_type = options.push_down_agg_type;
1024
223
    _push_down_count_columns = options.push_down_count_columns;
1025
223
    _initial_condition_cache_digest = options.condition_cache_digest;
1026
223
    _condition_cache_digest = _initial_condition_cache_digest;
1027
223
    _projected_columns = std::move(options.projected_columns);
1028
223
    if (supports_iceberg_scan_semantics_v1(_scan_params)) {
1029
76
        for (auto& projected_column : _projected_columns) {
1030
76
            const auto* schema_field = find_external_root_field(_scan_params, projected_column);
1031
76
            if (schema_field != nullptr) {
1032
36
                attach_full_schema_identity(
1033
36
                        &projected_column,
1034
36
                        build_schema_identity_from_external_field(*schema_field));
1035
36
            }
1036
76
        }
1037
68
    }
1038
223
    _system_properties = create_system_properties(_scan_params);
1039
223
    _mapper_options.mode = TableColumnMappingMode::BY_NAME;
1040
223
    _conjuncts = std::move(options.conjuncts);
1041
223
    return Status::OK();
1042
223
}
1043
1044
153
Status TableReader::_build_table_filters_from_conjuncts() {
1045
153
    _table_filters.clear();
1046
153
    _constant_pruning_safe_filter_count = 0;
1047
153
    bool in_safe_prefix = true;
1048
153
    for (const auto& conjunct : _conjuncts) {
1049
38
        DORIS_CHECK(conjunct != nullptr);
1050
38
        DORIS_CHECK(conjunct->root() != nullptr);
1051
        // `_table_filters` omits expressions without slot references, but such an expression still
1052
        // occupies a position in the row-level conjunct order. Record how many localized filters
1053
        // precede the first unsafe original conjunct so constant pruning cannot jump over a
1054
        // slotless non-deterministic/error-preserving barrier. Unsafe predicates remain solely on
1055
        // Scanner's original row-level path because localizing a clone would execute their state
1056
        // twice with independent state.
1057
38
        if (in_safe_prefix && !_is_safe_to_pre_execute(conjunct)) {
1058
5
            in_safe_prefix = false;
1059
5
        }
1060
38
        RETURN_IF_ERROR(
1061
38
                build_table_filters_from_conjunct(conjunct, _runtime_state, &_table_filters));
1062
38
        if (in_safe_prefix) {
1063
31
            _constant_pruning_safe_filter_count = _table_filters.size();
1064
31
        }
1065
38
    }
1066
153
    return Status::OK();
1067
153
}
1068
1069
namespace {
1070
1071
4
bool same_scan_projection(const LocalColumnIndex& lhs, const LocalColumnIndex& rhs) {
1072
4
    if (lhs.index != rhs.index || lhs.project_all_children != rhs.project_all_children ||
1073
4
        lhs.children.size() != rhs.children.size()) {
1074
0
        return false;
1075
0
    }
1076
4
    for (size_t index = 0; index < lhs.children.size(); ++index) {
1077
0
        if (!same_scan_projection(lhs.children[index], rhs.children[index])) {
1078
0
            return false;
1079
0
        }
1080
0
    }
1081
4
    return true;
1082
4
}
1083
1084
const LocalColumnIndex* find_scan_projection(const FileScanRequest& request,
1085
8
                                             LocalColumnId column_id) {
1086
13
    const auto find_by_id = [column_id](const std::vector<LocalColumnIndex>& projections) {
1087
13
        return std::ranges::find_if(projections, [column_id](const LocalColumnIndex& projection) {
1088
10
            return projection.column_id() == column_id;
1089
10
        });
1090
13
    };
1091
8
    auto it = find_by_id(request.predicate_columns);
1092
8
    if (it != request.predicate_columns.end()) {
1093
3
        return &*it;
1094
3
    }
1095
5
    it = find_by_id(request.non_predicate_columns);
1096
5
    return it == request.non_predicate_columns.end() ? nullptr : &*it;
1097
8
}
1098
1099
3
bool same_physical_scan_layout(const FileScanRequest& lhs, const FileScanRequest& rhs) {
1100
3
    if (lhs.local_positions != rhs.local_positions) {
1101
0
        return false;
1102
0
    }
1103
4
    for (const auto& [column_id, _] : lhs.local_positions) {
1104
4
        const auto* lhs_projection = find_scan_projection(lhs, column_id);
1105
4
        const auto* rhs_projection = find_scan_projection(rhs, column_id);
1106
4
        if (lhs_projection == nullptr || rhs_projection == nullptr ||
1107
4
            !same_scan_projection(*lhs_projection, *rhs_projection)) {
1108
0
            return false;
1109
0
        }
1110
4
    }
1111
3
    return true;
1112
3
}
1113
1114
} // namespace
1115
1116
8
Status TableReader::refresh_conjuncts(VExprContextSPtrs conjuncts) {
1117
8
    SCOPED_TIMER(_profile.total_timer);
1118
8
    SCOPED_TIMER(_profile.refresh_conjuncts_timer);
1119
8
    _conjuncts = std::move(conjuncts);
1120
8
    if (_data_reader.reader == nullptr) {
1121
        // The split is prepared but its physical reader has not opened yet. open_reader() will use
1122
        // this newest snapshot directly, so no pending request is needed.
1123
5
        return Status::OK();
1124
5
    }
1125
3
    if (!_data_reader.reader->supports_scan_request_refresh()) {
1126
0
        return Status::OK();
1127
0
    }
1128
1129
3
    RETURN_IF_ERROR(_build_table_filters_from_conjuncts());
1130
    // create_scan_request() rebuilds mapping projections in place. Build late predicates with an
1131
    // isolated mapper so the active row group cannot observe an unprepared or incompatible mapper
1132
    // before its physical request reaches the reader's safe activation boundary.
1133
3
    auto refreshed_mapper = _data_reader.reader->create_column_mapper(_mapper_options);
1134
3
    DORIS_CHECK(refreshed_mapper != nullptr);
1135
3
    RETURN_IF_ERROR(refreshed_mapper->create_mapping(_projected_columns, _partition_values,
1136
3
                                                     _data_reader.file_schema));
1137
3
    auto refreshed_request = std::make_shared<FileScanRequest>();
1138
3
    RETURN_IF_ERROR(refreshed_mapper->create_scan_request(
1139
3
            _table_filters, _projected_columns, refreshed_request.get(), _runtime_state,
1140
3
            _file_scan_request == nullptr ? nullptr : &_file_scan_request->local_positions));
1141
    // A refresh does not prove that every future runtime filter has arrived. Keep carrier values
1142
    // available whenever the split started with pending filters.
1143
3
    if (_push_down_agg_type == TPushAggOp::type::COUNT && _push_down_count_columns.has_value() &&
1144
3
        _push_down_count_columns->empty() && _all_runtime_filters_applied_for_split) {
1145
0
        for (const auto& column : refreshed_request->non_predicate_columns) {
1146
0
            refreshed_request->count_star_placeholder_columns.push_back(column.column_id());
1147
0
        }
1148
0
    }
1149
3
    RETURN_IF_ERROR(customize_file_scan_request(refreshed_request.get()));
1150
3
    if (_file_scan_request == nullptr ||
1151
3
        !same_physical_scan_layout(*refreshed_request, *_file_scan_request)) {
1152
        // A reader cannot reinterpret columns already materialized with another block layout.
1153
        // Keep scanner-level filtering as the correctness fallback for hidden slots or nested
1154
        // projections instead of switching an incompatible physical shape mid-file.
1155
0
        return Status::OK();
1156
0
    }
1157
3
    RETURN_IF_ERROR(_open_local_filter_exprs(*refreshed_request));
1158
1159
3
    if (_condition_cache_ctx != nullptr && !_condition_cache_ctx->is_hit) {
1160
        // Rows before and after a late RF were evaluated by different predicate snapshots. Such a
1161
        // partial MISS bitmap must never be published under either snapshot's cache key.
1162
0
        _condition_cache = nullptr;
1163
0
        _condition_cache_ctx = nullptr;
1164
0
        _data_reader.reader->set_condition_cache_context(nullptr);
1165
0
    }
1166
3
    {
1167
3
        SCOPED_TIMER(_profile.file_reader_total_timer);
1168
3
        SCOPED_TIMER(_profile.file_reader_refresh_timer);
1169
3
        RETURN_IF_ERROR(_data_reader.reader->queue_scan_request(refreshed_request));
1170
3
    }
1171
3
    _file_scan_request = std::move(refreshed_request);
1172
3
    return Status::OK();
1173
3
}
1174
1175
151
Status TableReader::_open_local_filter_exprs(const FileScanRequest& file_request) {
1176
151
    RowDescriptor row_desc;
1177
151
    for (const auto& conjunct : file_request.conjuncts) {
1178
27
        RETURN_IF_ERROR(conjunct->prepare(_runtime_state, row_desc));
1179
27
        RETURN_IF_ERROR(conjunct->open(_runtime_state));
1180
27
    }
1181
151
    for (const auto& delete_conjunct : file_request.delete_conjuncts) {
1182
56
        RETURN_IF_ERROR(delete_conjunct->prepare(_runtime_state, row_desc));
1183
56
        RETURN_IF_ERROR(delete_conjunct->open(_runtime_state));
1184
56
    }
1185
151
    return Status::OK();
1186
151
}
1187
1188
148
bool TableReader::_should_enable_condition_cache(const FileScanRequest& file_request) const {
1189
148
    if (_condition_cache_digest == 0 || _push_down_agg_type == TPushAggOp::type::COUNT ||
1190
148
        _current_file_description == std::nullopt || _data_reader.reader == nullptr) {
1191
141
        return false;
1192
141
    }
1193
    // Condition cache is populated by file readers after evaluating file-local row-level
1194
    // conjuncts. Metadata pruning can skip row groups/pages, but it does not produce a per-row
1195
    // survivor bitmap that can safely populate the cache.
1196
7
    if (file_request.conjuncts.empty()) {
1197
1
        return false;
1198
1
    }
1199
    // Delete files/deletion vectors are table-format state. They may change independently of the
1200
    // data file path/mtime/size used by the external cache key, so caching their result can become
1201
    // stale. Keep delete filtering enabled, but do not read or write condition cache.
1202
6
    if (_delete_rows != nullptr || _deletion_vector != nullptr ||
1203
6
        !file_request.delete_conjuncts.empty()) {
1204
1
        return false;
1205
1
    }
1206
    // Only scanner-driven splits provide a digest rebuilt from the exact RF snapshot. Keep the
1207
    // conservative behavior for standalone TableReader callers: their initial digest may describe
1208
    // only static predicate P and must not store P AND RF under that key.
1209
5
    return _condition_cache_digest_covers_current_split ||
1210
5
           !contains_runtime_filter(file_request.conjuncts);
1211
6
}
1212
1213
148
Status TableReader::_init_reader_condition_cache(const FileScanRequest& file_request) {
1214
148
    _condition_cache = nullptr;
1215
148
    _condition_cache_ctx = nullptr;
1216
148
    if (!_should_enable_condition_cache(file_request)) {
1217
144
        return Status::OK();
1218
144
    }
1219
1220
4
    auto* cache = segment_v2::ConditionCache::instance();
1221
4
    if (cache == nullptr) {
1222
0
        return Status::OK();
1223
0
    }
1224
4
    const auto& file = *_current_file_description;
1225
4
    _condition_cache_key = segment_v2::ConditionCache::ExternalCacheKey(
1226
4
            file.path, file.mtime, file.file_size, _condition_cache_digest, file.range_start_offset,
1227
4
            file.range_size,
1228
4
            segment_v2::ConditionCache::ExternalCacheKey::BASE_GRANULE_AWARE_VERSION);
1229
1230
4
    segment_v2::ConditionCacheHandle handle;
1231
4
    const bool condition_cache_hit = cache->lookup(_condition_cache_key, &handle);
1232
4
    if (condition_cache_hit) {
1233
0
        _condition_cache = handle.get_filter_result();
1234
0
        ++_condition_cache_hit_count;
1235
4
    } else {
1236
4
        const int64_t total_rows = _data_reader.reader->get_total_rows();
1237
4
        if (total_rows <= 0) {
1238
0
            return Status::OK();
1239
0
        }
1240
        // Add one guard granule for split ranges that start in the middle of a granule. A guard
1241
        // false bit beyond the real range never overlaps real rows, but avoids boundary overflow
1242
        // when a reader marks the last partial granule.
1243
4
        const size_t num_granules = (total_rows + ConditionCacheContext::GRANULE_SIZE - 1) /
1244
4
                                    ConditionCacheContext::GRANULE_SIZE;
1245
4
        _condition_cache = std::make_shared<std::vector<bool>>(num_granules + 1, false);
1246
4
    }
1247
1248
4
    if (_condition_cache != nullptr) {
1249
4
        _condition_cache_ctx = std::make_shared<ConditionCacheContext>();
1250
4
        _condition_cache_ctx->is_hit = condition_cache_hit;
1251
4
        _condition_cache_ctx->filter_result = _condition_cache;
1252
4
        _condition_cache_ctx->num_granules = _condition_cache->size();
1253
4
        if (condition_cache_hit) {
1254
0
            _condition_cache_ctx->base_granule = handle.get_base_granule();
1255
0
        }
1256
4
        _data_reader.reader->set_condition_cache_context(_condition_cache_ctx);
1257
4
    }
1258
4
    return Status::OK();
1259
4
}
1260
1261
150
void TableReader::_finalize_reader_condition_cache() {
1262
150
    if (_condition_cache_ctx == nullptr || _condition_cache_ctx->is_hit) {
1263
146
        _condition_cache = nullptr;
1264
146
        _condition_cache_ctx = nullptr;
1265
146
        return;
1266
146
    }
1267
    // LIMIT or scanner cancellation may close a reader before all selected row ranges are visited.
1268
    // Unvisited granules remain false in a MISS bitmap, so inserting a partial bitmap would make a
1269
    // later HIT skip valid rows. Only publish cache entries after the physical reader reaches EOF.
1270
4
    if (!_current_reader_reached_eof) {
1271
2
        _condition_cache = nullptr;
1272
2
        _condition_cache_ctx = nullptr;
1273
2
        return;
1274
2
    }
1275
2
    DORIS_CHECK(_condition_cache_ctx->num_granules <= _condition_cache->size());
1276
2
    _condition_cache->resize(_condition_cache_ctx->num_granules);
1277
2
    segment_v2::ConditionCache::instance()->insert(
1278
2
            _condition_cache_key, std::move(_condition_cache), _condition_cache_ctx->base_granule);
1279
2
    _condition_cache = nullptr;
1280
2
    _condition_cache_ctx = nullptr;
1281
2
}
1282
1283
211
Status TableReader::create_next_reader(bool* eos) {
1284
211
    SCOPED_TIMER(_profile.create_reader_timer);
1285
211
    DCHECK(_data_reader.reader == nullptr);
1286
211
    if (_current_task == nullptr) {
1287
60
        *eos = true;
1288
60
        return Status::OK();
1289
60
    }
1290
1291
151
    RETURN_IF_ERROR(create_file_reader(&_data_reader.reader));
1292
151
    DORIS_CHECK(_data_reader.reader != nullptr);
1293
151
    if (_batch_size > 0) {
1294
0
        _data_reader.reader->set_batch_size(_batch_size);
1295
0
    }
1296
151
    Status st;
1297
151
    {
1298
151
        SCOPED_TIMER(_profile.file_reader_total_timer);
1299
151
        SCOPED_TIMER(_profile.file_reader_init_timer);
1300
151
        st = _data_reader.reader->init(_runtime_state);
1301
151
    }
1302
151
    if (!st.ok()) {
1303
1
        if (_io_ctx != nullptr && _io_ctx->should_stop && st.is<ErrorCode::END_OF_FILE>()) {
1304
0
            *eos = true;
1305
0
            _data_reader.reader.reset();
1306
0
            return Status::OK();
1307
0
        }
1308
1
        return st;
1309
1
    }
1310
150
    st = open_reader();
1311
150
    if (!st.ok()) {
1312
1
        if (_io_ctx != nullptr && _io_ctx->should_stop && st.is<ErrorCode::END_OF_FILE>()) {
1313
0
            *eos = true;
1314
0
            _data_reader.reader.reset();
1315
0
            return Status::OK();
1316
0
        }
1317
1
        return st;
1318
1
    }
1319
149
    if (_data_reader.reader == nullptr) {
1320
1
        *eos = _current_task == nullptr;
1321
1
        return Status::OK();
1322
1
    }
1323
148
    *eos = false;
1324
148
    return Status::OK();
1325
149
}
1326
1327
122
Status TableReader::create_file_reader(std::unique_ptr<FileReader>* reader) {
1328
122
    DORIS_CHECK(reader != nullptr);
1329
122
    const bool enable_mapping_timestamp_tz = _scan_params != nullptr &&
1330
122
                                             _scan_params->__isset.enable_mapping_timestamp_tz &&
1331
122
                                             _scan_params->enable_mapping_timestamp_tz;
1332
122
    const bool enable_mapping_varbinary = _scan_params != nullptr &&
1333
122
                                          _scan_params->__isset.enable_mapping_varbinary &&
1334
122
                                          _scan_params->enable_mapping_varbinary;
1335
122
    if (_format == FileFormat::PARQUET) {
1336
        // V2 must honor the scan contract directly; otherwise Hive STRING columns backed by an
1337
        // unannotated BYTE_ARRAY are silently exposed as VARBINARY and predicate bytes no longer
1338
        // match the table type.
1339
111
        *reader = std::make_unique<format::parquet::ParquetReader>(
1340
111
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
1341
111
                _global_rowid_context, enable_mapping_timestamp_tz, enable_mapping_varbinary);
1342
111
        return Status::OK();
1343
111
    }
1344
11
    if (_format == FileFormat::ORC) {
1345
11
        *reader = std::make_unique<format::orc::OrcReader>(
1346
11
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
1347
11
                _global_rowid_context, enable_mapping_timestamp_tz);
1348
11
        return Status::OK();
1349
11
    }
1350
0
    if (_format == FileFormat::CSV) {
1351
0
        if (_file_slot_descs == nullptr) {
1352
0
            return Status::InvalidArgument("CSV reader requires file slot descriptors");
1353
0
        }
1354
        // CSV has no embedded schema. TableReader owns table-level mapping, while CsvReader needs
1355
        // only the physical file slots plus scan text parameters to build a file-local schema.
1356
        // Non-file columns such as partitions/defaults/virtual row ids are intentionally excluded
1357
        // from `_file_slot_descs` and are materialized during finalize_chunk().
1358
0
        *reader = std::make_unique<format::csv::CsvReader>(
1359
0
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
1360
0
                _scan_params, *_file_slot_descs, _current_range_compress_type,
1361
0
                _current_range_load_id);
1362
0
        return Status::OK();
1363
0
    }
1364
0
    if (_format == FileFormat::TEXT) {
1365
0
        if (_file_slot_descs == nullptr) {
1366
0
            return Status::InvalidArgument("Text reader requires file slot descriptors");
1367
0
        }
1368
        // Text files have no embedded schema. As with CSV, TableReader handles table-level mapping
1369
        // and only passes physical file slots to the v2 TextReader.
1370
0
        *reader = std::make_unique<format::text::TextReader>(
1371
0
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
1372
0
                _scan_params, *_file_slot_descs, _current_range_compress_type,
1373
0
                _current_range_load_id);
1374
0
        return Status::OK();
1375
0
    }
1376
0
    if (_format == FileFormat::JSON) {
1377
0
        if (_file_slot_descs == nullptr) {
1378
0
            return Status::InvalidArgument("JSON reader requires file slot descriptors");
1379
0
        }
1380
0
        *reader = std::make_unique<format::json::JsonReader>(
1381
0
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
1382
0
                _scan_params, _current_file_range_desc, *_file_slot_descs,
1383
0
                _current_range_compress_type, _current_range_load_id);
1384
0
        return Status::OK();
1385
0
    }
1386
0
    if (_format == FileFormat::NATIVE) {
1387
0
        *reader = std::make_unique<format::native::NativeReader>(
1388
0
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile);
1389
0
        return Status::OK();
1390
0
    }
1391
0
    return Status::NotSupported("TableReader does not support file format {}",
1392
0
                                file_format_to_string(_format));
1393
0
}
1394
1395
183
std::unique_ptr<io::FileDescription> create_file_description(const TFileRangeDesc& range) {
1396
183
    auto file_description = std::make_unique<io::FileDescription>();
1397
183
    file_description->path = range.path;
1398
183
    file_description->file_size = range.__isset.file_size ? range.file_size : -1;
1399
183
    file_description->mtime = range.__isset.modification_time ? range.modification_time : 0;
1400
183
    file_description->range_start_offset = range.__isset.start_offset ? range.start_offset : 0;
1401
183
    file_description->range_size = range.__isset.size ? range.size : -1;
1402
183
    if (range.__isset.fs_name) {
1403
5
        file_description->fs_name = range.fs_name;
1404
5
    }
1405
183
    if (range.__isset.file_cache_admission) {
1406
0
        file_description->file_cache_admission = range.file_cache_admission;
1407
0
    }
1408
183
    return file_description;
1409
183
}
1410
1411
184
Status TableReader::prepare_split(const SplitReadOptions& options) {
1412
184
    SCOPED_TIMER(_profile.total_timer);
1413
184
    SCOPED_TIMER(_profile.prepare_split_timer);
1414
184
    _current_split_pruned = false;
1415
184
    _all_runtime_filters_applied_for_split = options.all_runtime_filters_applied;
1416
184
    _condition_cache_digest_covers_current_split = options.condition_cache_digest.has_value();
1417
184
    if (options.condition_cache_digest.has_value()) {
1418
        // The split snapshot may include RFs that arrived after TableReader::init(). Use the digest
1419
        // computed from that exact snapshot. Example: an initial P digest must not be used to store
1420
        // the bitmap for P AND late RF{7, 9}; the scanner supplies digest(P AND RF{7, 9}) here.
1421
1
        _condition_cache_digest = *options.condition_cache_digest;
1422
183
    } else {
1423
        // An explicit scanner digest is split-scoped. Restore the init-time digest when a later
1424
        // standalone split omits it instead of leaking the previous split's RF payload into its key.
1425
183
        _condition_cache_digest = _initial_condition_cache_digest;
1426
183
    }
1427
184
    if (options.conjuncts.has_value()) {
1428
2
        _conjuncts = *options.conjuncts;
1429
2
    }
1430
    // Update to current split format to handle ORC/PARQUET files in one table.
1431
184
    _format = options.current_split_format;
1432
184
    _partition_values = std::move(options.partition_values);
1433
184
    _current_task.reset();
1434
184
    _current_file_description.reset();
1435
184
    _current_file_range_desc = options.current_range;
1436
184
    _current_range_compress_type = options.current_range.__isset.compress_type
1437
184
                                           ? options.current_range.compress_type
1438
184
                                           : TFileCompressType::UNKNOWN;
1439
184
    _current_range_load_id = options.current_range.__isset.load_id
1440
184
                                     ? std::make_optional(options.current_range.load_id)
1441
184
                                     : std::nullopt;
1442
184
    _global_rowid_context = options.global_rowid_context;
1443
184
    _delete_rows = nullptr;
1444
184
    _deletion_vector = nullptr;
1445
184
    _aggregate_pushdown_tried = false;
1446
184
    _remaining_table_level_count = -1;
1447
184
    _remaining_file_level_count = -1;
1448
184
    _current_split_uses_metadata_count = false;
1449
184
    _current_reader_reached_eof = false;
1450
184
    RETURN_IF_ERROR(_evaluate_partition_prune_conjuncts(options.partition_prune_conjuncts,
1451
184
                                                        &_current_split_pruned));
1452
184
    if (_current_split_pruned) {
1453
1
        COUNTER_UPDATE(_profile.runtime_filter_partition_pruned_range_counter, 1);
1454
1
        return Status::OK();
1455
1
    }
1456
183
    _current_task = std::make_unique<ScanTask>();
1457
183
    _current_task->data_file = create_file_description(options.current_range);
1458
183
    _current_file_description = *_current_task->data_file;
1459
    // A table-level row count is only equivalent to scanning the split when no row predicate is
1460
    // active and no predicate can arrive later. The metadata path can return several batches for
1461
    // one split; after its first synthetic batch there is no way to recover the real rows if a
1462
    // runtime filter arrives before the next scheduler turn.
1463
    // Table-level metadata only contains the number of rows; it cannot evaluate an expression or
1464
    // the NULL state of a COUNT argument. Require the new FE's explicit empty argument list, which
1465
    // means COUNT(*)/COUNT(1). A non-empty list means COUNT(col), while nullopt comes from an old FE
1466
    // whose COUNT semantics are unknown during a BE-first rolling upgrade.
1467
183
    if (_push_down_agg_type == TPushAggOp::type::COUNT && _push_down_count_columns.has_value() &&
1468
183
        _push_down_count_columns->empty() && options.all_runtime_filters_applied &&
1469
183
        _conjuncts.empty() && options.current_range.__isset.table_format_params &&
1470
183
        options.current_range.table_format_params.__isset.table_level_row_count) {
1471
3
        DORIS_CHECK(options.current_range.table_format_params.table_level_row_count >= -1);
1472
3
        _remaining_table_level_count =
1473
3
                options.current_range.table_format_params.table_level_row_count;
1474
3
        _current_split_uses_metadata_count = _is_table_level_count_active();
1475
3
    }
1476
183
    if (_is_table_level_count_active()) {
1477
2
        return Status::OK();
1478
2
    }
1479
181
    return _parse_delete_predicates(options);
1480
183
}
1481
1482
Status TableReader::_evaluate_partition_prune_conjuncts(const VExprContextSPtrs& conjuncts,
1483
184
                                                        bool* can_filter_all) {
1484
184
    DORIS_CHECK(can_filter_all != nullptr);
1485
184
    SCOPED_TIMER(_profile.runtime_filter_partition_prune_timer);
1486
184
    *can_filter_all = false;
1487
184
    if (conjuncts.empty() || _partition_values.empty()) {
1488
181
        return Status::OK();
1489
181
    }
1490
1491
3
    VExprContextSPtrs partition_conjuncts;
1492
3
    for (const auto& conjunct : conjuncts) {
1493
3
        DORIS_CHECK(conjunct != nullptr);
1494
3
        DORIS_CHECK(conjunct->root() != nullptr);
1495
        // Keep only the safe prefix of the original conjunct order. If an unsafe conjunct is
1496
        // skipped, a later predicate could prune the split before the unsafe one reaches its
1497
        // normal row-level evaluation point.
1498
3
        if (!_is_safe_to_pre_execute(conjunct)) {
1499
1
            break;
1500
1
        }
1501
2
        std::set<GlobalIndex> global_indices;
1502
2
        collect_global_indices(conjunct->root(), &global_indices);
1503
2
        if (global_indices.empty()) {
1504
0
            continue;
1505
0
        }
1506
2
        const bool partition_only = std::ranges::all_of(global_indices, [&](GlobalIndex index) {
1507
2
            if (index.value() >= _projected_columns.size()) {
1508
0
                return false;
1509
0
            }
1510
2
            const auto& column = _projected_columns[index.value()];
1511
2
            return column.is_partition_key &&
1512
2
                   find_partition_value(column, _partition_values) != nullptr;
1513
2
        });
1514
2
        if (partition_only) {
1515
2
            partition_conjuncts.push_back(conjunct);
1516
2
        }
1517
2
    }
1518
3
    if (partition_conjuncts.empty()) {
1519
1
        return Status::OK();
1520
1
    }
1521
1522
2
    Block block;
1523
2
    RETURN_IF_ERROR(_build_partition_prune_block(&block));
1524
2
    RowDescriptor row_desc;
1525
2
    for (const auto& conjunct : partition_conjuncts) {
1526
2
        RETURN_IF_ERROR(conjunct->prepare(_runtime_state, row_desc));
1527
2
        RETURN_IF_ERROR(conjunct->open(_runtime_state));
1528
2
    }
1529
2
    IColumn::Filter result_filter(block.rows(), 1);
1530
2
    return VExprContext::execute_conjuncts(partition_conjuncts, nullptr, &block, &result_filter,
1531
2
                                           can_filter_all);
1532
2
}
1533
1534
67
bool TableReader::_is_safe_to_pre_execute(const VExprContextSPtr& conjunct) {
1535
67
    DORIS_CHECK(conjunct != nullptr);
1536
67
    DORIS_CHECK(conjunct->root() != nullptr);
1537
67
    const auto root = conjunct->root();
1538
67
    const auto impl = root->get_impl();
1539
67
    const auto predicate = impl != nullptr ? impl : root;
1540
    // Split pruning evaluates a predicate once before any file rows are read. Reordering
1541
    // non-deterministic or error-preserving expressions can change their row-level semantics,
1542
    // even when every referenced slot is a partition column or maps to a constant entry.
1543
67
    return predicate->is_safe_to_execute_on_selected_rows();
1544
67
}
1545
1546
2
Status TableReader::_build_partition_prune_block(Block* block) const {
1547
2
    DORIS_CHECK(block != nullptr);
1548
2
    DORIS_CHECK(!_projected_columns.empty());
1549
2
    block->clear();
1550
2
    for (const auto& column : _projected_columns) {
1551
2
        DORIS_CHECK(column.type != nullptr);
1552
2
        ColumnPtr value_column = column.type->create_column_const_with_default_value(1);
1553
2
        if (column.is_partition_key) {
1554
2
            const auto* partition_value = find_partition_value(column, _partition_values);
1555
2
            if (partition_value != nullptr) {
1556
2
                value_column = column.type->create_column_const(1, *partition_value);
1557
2
            }
1558
2
        }
1559
2
        block->insert({std::move(value_column), column.type, column.name});
1560
2
    }
1561
2
    return Status::OK();
1562
2
}
1563
1564
181
Status TableReader::_parse_delete_predicates(const SplitReadOptions& options) {
1565
181
    DeleteFileDesc desc {.fs_name = options.current_range.fs_name};
1566
181
    bool has_delete_file = false;
1567
181
    RETURN_IF_ERROR(_parse_deletion_vector_file(options.current_range.table_format_params, &desc,
1568
181
                                                &has_delete_file));
1569
181
    if (has_delete_file) {
1570
7
        DORIS_CHECK(options.cache != nullptr);
1571
7
        Status create_status = Status::OK();
1572
1573
7
        bool decoded_cache_hit = false;
1574
7
        _deletion_vector = options.cache->get<DeletionVector>(
1575
7
                desc.key,
1576
7
                [&]() -> DeletionVector* {
1577
7
                    auto deletion_vector = std::make_unique<DeletionVector>();
1578
1579
7
                    DeletionVectorReader dv_reader(_runtime_state, _scanner_profile, *_scan_params,
1580
7
                                                   desc, _io_ctx.get());
1581
7
                    create_status = dv_reader.open();
1582
7
                    if (!create_status.ok()) [[unlikely]] {
1583
0
                        return nullptr;
1584
0
                    }
1585
1586
7
                    size_t bytes_read = desc.size;
1587
7
                    std::vector<char> buffer(bytes_read);
1588
7
                    DBUG_EXECUTE_IF("TableReader.parse_deletion_vector.io_error", {
1589
7
                        create_status =
1590
7
                                Status::IOError("injected format v2 deletion vector read failure");
1591
7
                        return nullptr;
1592
7
                    });
1593
6
                    DBUG_EXECUTE_IF("TableReader.parse_deletion_vector.should_stop", {
1594
6
                        create_status = Status::EndOfFile("stop read.");
1595
6
                        return nullptr;
1596
6
                    });
1597
5
                    create_status =
1598
5
                            dv_reader.read_at(desc.start_offset, {buffer.data(), bytes_read});
1599
5
                    const auto& file_cache_stats = dv_reader.file_cache_statistics();
1600
5
                    COUNTER_UPDATE(_profile.dv_file_cache_hit_count,
1601
5
                                   file_cache_stats.num_local_io_total);
1602
5
                    COUNTER_UPDATE(_profile.dv_file_cache_miss_count,
1603
5
                                   file_cache_stats.num_remote_io_total);
1604
5
                    COUNTER_UPDATE(_profile.dv_file_cache_peer_read_count,
1605
5
                                   file_cache_stats.num_peer_io_total);
1606
5
                    if (!create_status.ok()) [[unlikely]] {
1607
0
                        return nullptr;
1608
0
                    }
1609
1610
5
                    const char* buf = buffer.data();
1611
5
                    SCOPED_TIMER(_profile.parse_delete_file_time);
1612
5
                    create_status = parse_deletion_vector(buf, bytes_read, desc.format,
1613
5
                                                          deletion_vector.get());
1614
5
                    if (!create_status.ok()) [[unlikely]] {
1615
1
                        return nullptr;
1616
1
                    }
1617
4
                    COUNTER_UPDATE(_profile.num_delete_rows, deletion_vector->cardinality());
1618
4
                    return deletion_vector.release();
1619
5
                },
1620
7
                &decoded_cache_hit);
1621
7
        RETURN_IF_ERROR(create_status);
1622
4
        COUNTER_UPDATE(decoded_cache_hit ? _profile.decoded_dv_cache_hit_count
1623
4
                                         : _profile.decoded_dv_cache_miss_count,
1624
4
                       1);
1625
4
    }
1626
1627
178
    return Status::OK();
1628
181
}
1629
} // namespace doris::format