Coverage Report

Created: 2026-07-27 07:04

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
3.00M
const schema::external::TField* get_field_ptr(const schema::external::TFieldPtr& field_ptr) {
144
3.00M
    if (!field_ptr.__isset.field_ptr || field_ptr.field_ptr == nullptr) {
145
0
        return nullptr;
146
0
    }
147
3.00M
    return field_ptr.field_ptr.get();
148
3.00M
}
149
150
132k
ColumnDefinition build_schema_identity_from_external_field(const schema::external::TField& field) {
151
132k
    ColumnDefinition identity;
152
132k
    if (field.__isset.id) {
153
132k
        identity.identifier = Field::create_field<TYPE_INT>(field.id);
154
132k
    }
155
132k
    identity.name = field.__isset.name ? field.name : "";
156
132k
    identity.name_mapping =
157
132k
            field.__isset.name_mapping ? field.name_mapping : std::vector<std::string> {};
158
132k
    identity.has_name_mapping =
159
132k
            field.__isset.name_mapping_is_authoritative && field.name_mapping_is_authoritative;
160
132k
    if (!field.__isset.nestedField) {
161
103k
        return identity;
162
103k
    }
163
28.6k
    if (field.nestedField.__isset.struct_field && field.nestedField.struct_field.__isset.fields) {
164
26.3k
        for (const auto& child_ptr : field.nestedField.struct_field.fields) {
165
26.4k
            if (const auto* child = get_field_ptr(child_ptr); child != nullptr) {
166
26.4k
                identity.children.push_back(build_schema_identity_from_external_field(*child));
167
26.4k
            }
168
26.3k
        }
169
18.1k
    } else if (field.nestedField.__isset.array_field &&
170
18.1k
               field.nestedField.array_field.__isset.item_field) {
171
10.0k
        if (const auto* child = get_field_ptr(field.nestedField.array_field.item_field);
172
10.0k
            child != nullptr) {
173
10.0k
            identity.children.push_back(build_schema_identity_from_external_field(*child));
174
10.0k
            identity.children.back().name = "element";
175
10.0k
        }
176
10.0k
    } else if (field.nestedField.__isset.map_field) {
177
8.36k
        if (field.nestedField.map_field.__isset.key_field) {
178
8.36k
            if (const auto* child = get_field_ptr(field.nestedField.map_field.key_field);
179
8.36k
                child != nullptr) {
180
8.36k
                identity.children.push_back(build_schema_identity_from_external_field(*child));
181
8.36k
                identity.children.back().name = "key";
182
8.36k
            }
183
8.36k
        }
184
8.36k
        if (field.nestedField.map_field.__isset.value_field) {
185
8.36k
            if (const auto* child = get_field_ptr(field.nestedField.map_field.value_field);
186
8.37k
                child != nullptr) {
187
8.37k
                identity.children.push_back(build_schema_identity_from_external_field(*child));
188
8.37k
                identity.children.back().name = "value";
189
8.37k
            }
190
8.36k
        }
191
8.36k
    }
192
28.6k
    return identity;
193
132k
}
194
195
const ColumnDefinition* find_identity_child(const ColumnDefinition& projected_child,
196
48.2k
                                            const ColumnDefinition& identity_parent) {
197
48.2k
    const auto child_it = std::ranges::find_if(
198
80.0k
            identity_parent.children, [&](const ColumnDefinition& identity_child) {
199
80.0k
                if (projected_child.has_identifier_field_id() &&
200
80.0k
                    identity_child.has_identifier_field_id()) {
201
79.8k
                    return projected_child.get_identifier_field_id() ==
202
79.8k
                           identity_child.get_identifier_field_id();
203
79.8k
                }
204
132
                if (to_lower(projected_child.name) == to_lower(identity_child.name)) {
205
0
                    return true;
206
0
                }
207
132
                return std::ranges::any_of(
208
132
                        identity_child.name_mapping, [&](const std::string& alias) {
209
0
                            return to_lower(projected_child.name) == to_lower(alias);
210
0
                        });
211
132
            });
212
48.2k
    return child_it == identity_parent.children.end() ? nullptr : &*child_it;
213
48.2k
}
214
215
126k
void attach_full_schema_identity(ColumnDefinition* projected, const ColumnDefinition& identity) {
216
126k
    DORIS_CHECK(projected != nullptr);
217
    // Access-path children control materialization, but wrapper discovery needs sibling IDs that
218
    // were pruned from that projection. Keep the complete identity tree on a separate channel.
219
126k
    projected->identity_children = identity.children;
220
126k
    for (auto& projected_child : projected->children) {
221
48.2k
        if (const auto* identity_child = find_identity_child(projected_child, identity);
222
48.2k
            identity_child != nullptr) {
223
48.1k
            attach_full_schema_identity(&projected_child, *identity_child);
224
48.1k
        }
225
48.2k
    }
226
126k
}
227
228
60.2k
void clear_initial_default_metadata(ColumnDefinition* column) {
229
60.2k
    DORIS_CHECK(column != nullptr);
230
60.2k
    column->initial_default_value.reset();
231
60.2k
    column->initial_default_value_is_base64 = false;
232
60.2k
    for (auto& child : column->children) {
233
29.6k
        clear_initial_default_metadata(&child);
234
29.6k
    }
235
60.2k
}
236
237
1.54M
bool external_field_matches_name(const schema::external::TField& field, const std::string& name) {
238
1.54M
    if (field.__isset.name && to_lower(field.name) == to_lower(name)) {
239
61.7k
        return true;
240
61.7k
    }
241
1.48M
    return field.__isset.name_mapping &&
242
1.48M
           std::ranges::any_of(field.name_mapping, [&](const std::string& alias) {
243
7
               return to_lower(alias) == to_lower(name);
244
7
           });
245
1.54M
}
246
247
DataTypePtr find_struct_child_type_by_external_field(const DataTypeStruct& struct_type,
248
33.8k
                                                     const schema::external::TField& field) {
249
70.8k
    for (size_t field_idx = 0; field_idx < struct_type.get_elements().size(); ++field_idx) {
250
68.1k
        if (external_field_matches_name(field, struct_type.get_element_name(field_idx))) {
251
31.1k
            return struct_type.get_element(field_idx);
252
31.1k
        }
253
68.1k
    }
254
2.67k
    return nullptr;
255
33.8k
}
256
257
DataTypePtr restore_current_primitive_type(const schema::external::TField& field,
258
189k
                                           DataTypePtr fallback_type) {
259
189k
    if (!field.__isset.type) {
260
16
        return fallback_type;
261
16
    }
262
189k
    const auto primitive_type = thrift_to_type(field.type.type);
263
189k
    if (is_complex_type(primitive_type)) {
264
44.3k
        return fallback_type;
265
44.3k
    }
266
    // The delete file can expose an older physical type, but initial defaults belong to the
267
    // current table field. Restore that type from FE before parsing the default and let the table
268
    // reader apply the normal promotion cast to the delete-key type.
269
145k
    return DataTypeFactory::instance().create_data_type(
270
145k
            primitive_type, false, field.type.__isset.precision ? field.type.precision : 0,
271
145k
            field.type.__isset.scale ? field.type.scale : 0,
272
145k
            field.type.__isset.len ? field.type.len : -1);
273
189k
}
274
275
ColumnDefinition build_schema_column_from_external_field(const schema::external::TField& field,
276
189k
                                                         DataTypePtr type) {
277
189k
    type = restore_current_primitive_type(field, std::move(type));
278
189k
    ColumnDefinition column {
279
18.4E
            .identifier = field.__isset.id ? Field::create_field<TYPE_INT>(field.id) : Field {},
280
189k
            .name = field.__isset.name ? field.name : "",
281
189k
            .name_mapping =
282
189k
                    field.__isset.name_mapping ? field.name_mapping : std::vector<std::string> {},
283
189k
            .has_name_mapping = field.__isset.name_mapping_is_authoritative &&
284
189k
                                field.name_mapping_is_authoritative,
285
189k
            .type = std::move(type),
286
189k
            .children = {},
287
189k
            .default_expr = nullptr,
288
189k
            .initial_default_value = field.__isset.initial_default_value
289
189k
                                             ? std::make_optional(field.initial_default_value)
290
189k
                                             : std::nullopt,
291
189k
            .initial_default_value_is_base64 = field.__isset.initial_default_value_is_base64 &&
292
189k
                                               field.initial_default_value_is_base64,
293
189k
            .is_partition_key = false,
294
189k
    };
295
189k
    if (column.type == nullptr || !field.__isset.nestedField) {
296
145k
        return column;
297
145k
    }
298
299
44.2k
    const auto nested_type = remove_nullable(column.type);
300
44.2k
    switch (nested_type->get_primitive_type()) {
301
13.3k
    case TYPE_STRUCT: {
302
13.3k
        if (!field.nestedField.__isset.struct_field ||
303
13.3k
            !field.nestedField.struct_field.__isset.fields) {
304
0
            return column;
305
0
        }
306
13.3k
        const auto& struct_type = assert_cast<const DataTypeStruct&>(*nested_type);
307
33.8k
        for (const auto& child_ptr : field.nestedField.struct_field.fields) {
308
33.8k
            const auto* child_field = get_field_ptr(child_ptr);
309
33.8k
            if (child_field == nullptr || !child_field->__isset.name) {
310
0
                continue;
311
0
            }
312
33.8k
            auto child_type = find_struct_child_type_by_external_field(struct_type, *child_field);
313
33.8k
            if (child_type == nullptr) {
314
2.67k
                continue;
315
2.67k
            }
316
31.1k
            column.children.push_back(
317
31.1k
                    build_schema_column_from_external_field(*child_field, child_type));
318
31.1k
        }
319
13.3k
        break;
320
13.3k
    }
321
13.0k
    case TYPE_ARRAY: {
322
13.0k
        if (!field.nestedField.__isset.array_field ||
323
13.0k
            !field.nestedField.array_field.__isset.item_field) {
324
0
            return column;
325
0
        }
326
13.0k
        const auto* item_field = get_field_ptr(field.nestedField.array_field.item_field);
327
13.0k
        if (item_field == nullptr) {
328
0
            return column;
329
0
        }
330
13.0k
        const auto& array_type = assert_cast<const DataTypeArray&>(*nested_type);
331
13.0k
        auto child =
332
13.0k
                build_schema_column_from_external_field(*item_field, array_type.get_nested_type());
333
13.0k
        child.name = "element";
334
13.0k
        if (child.has_identifier_name()) {
335
0
            child.identifier = Field::create_field<TYPE_STRING>(child.name);
336
0
        }
337
13.0k
        column.children.push_back(std::move(child));
338
13.0k
        break;
339
13.0k
    }
340
17.8k
    case TYPE_MAP: {
341
17.8k
        if (!field.nestedField.__isset.map_field ||
342
17.8k
            !field.nestedField.map_field.__isset.key_field ||
343
17.8k
            !field.nestedField.map_field.__isset.value_field) {
344
0
            return column;
345
0
        }
346
17.8k
        const auto& map_type = assert_cast<const DataTypeMap&>(*nested_type);
347
17.8k
        const auto* key_field = get_field_ptr(field.nestedField.map_field.key_field);
348
17.8k
        if (key_field != nullptr) {
349
17.8k
            auto child =
350
17.8k
                    build_schema_column_from_external_field(*key_field, map_type.get_key_type());
351
17.8k
            child.name = "key";
352
17.8k
            if (child.has_identifier_name()) {
353
0
                child.identifier = Field::create_field<TYPE_STRING>(child.name);
354
0
            }
355
17.8k
            column.children.push_back(std::move(child));
356
17.8k
        }
357
17.8k
        const auto* value_field = get_field_ptr(field.nestedField.map_field.value_field);
358
17.8k
        if (value_field != nullptr) {
359
17.8k
            auto child = build_schema_column_from_external_field(*value_field,
360
17.8k
                                                                 map_type.get_value_type());
361
17.8k
            child.name = "value";
362
17.8k
            if (child.has_identifier_name()) {
363
0
                child.identifier = Field::create_field<TYPE_STRING>(child.name);
364
0
            }
365
17.8k
            column.children.push_back(std::move(child));
366
17.8k
        }
367
17.8k
        break;
368
17.8k
    }
369
0
    default:
370
0
        break;
371
44.2k
    }
372
44.3k
    return column;
373
44.2k
}
374
375
const schema::external::TField* find_external_root_field(const TFileScanRangeParams* params,
376
370k
                                                         const ColumnDefinition& column) {
377
370k
    if (params == nullptr || !params->__isset.history_schema_info ||
378
370k
        params->history_schema_info.empty()) {
379
181k
        return nullptr;
380
181k
    }
381
189k
    const auto* schema = &params->history_schema_info.front();
382
189k
    if (params->__isset.current_schema_id) {
383
189k
        for (const auto& candidate_schema : params->history_schema_info) {
384
189k
            if (candidate_schema.__isset.schema_id &&
385
189k
                candidate_schema.schema_id == params->current_schema_id) {
386
189k
                schema = &candidate_schema;
387
189k
                break;
388
189k
            }
389
189k
        }
390
189k
    }
391
189k
    if (!schema->__isset.root_field || !schema->root_field.__isset.fields) {
392
0
        return nullptr;
393
0
    }
394
189k
    if (!supports_iceberg_scan_semantics_v1(params)) {
395
        // Old BEs used one ordered current-name/alias pass. Preserve that result for old-FE plans
396
        // until the explicit scan-semantics marker makes exact-name precedence cluster-wide.
397
1.48M
        for (const auto& field_ptr : schema->root_field.fields) {
398
1.48M
            const auto* field = get_field_ptr(field_ptr);
399
1.48M
            if (field != nullptr && external_field_matches_name(*field, column.name)) {
400
30.6k
                return field;
401
30.6k
            }
402
1.48M
        }
403
18.4E
        return nullptr;
404
30.6k
    }
405
    // A reused name identifies the newly added field, not an older sibling that retained that
406
    // spelling as an alias. Exhaust exact current names before consulting historical aliases.
407
1.39M
    for (const auto& field_ptr : schema->root_field.fields) {
408
1.39M
        const auto* field = get_field_ptr(field_ptr);
409
1.39M
        if (field != nullptr && field->__isset.name &&
410
1.39M
            to_lower(field->name) == to_lower(column.name)) {
411
158k
            return field;
412
158k
        }
413
1.39M
    }
414
3.53k
    for (const auto& field_ptr : schema->root_field.fields) {
415
3.53k
        const auto* field = get_field_ptr(field_ptr);
416
3.53k
        if (field != nullptr && field->__isset.name_mapping &&
417
3.53k
            std::ranges::any_of(field->name_mapping, [&](const std::string& alias) {
418
0
                return to_lower(alias) == to_lower(column.name);
419
0
            })) {
420
0
            return field;
421
0
        }
422
3.53k
    }
423
483
    return nullptr;
424
483
}
425
426
2
std::string expr_context_debug_string(const VExprContextSPtr& context) {
427
2
    if (context == nullptr) {
428
0
        return "null";
429
0
    }
430
2
    const auto root = context->root();
431
2
    if (root == nullptr) {
432
0
        return "VExprContext{root=null}";
433
0
    }
434
2
    std::ostringstream out;
435
2
    out << "VExprContext{root_name=" << root->expr_name() << ", root_debug=" << root->debug_string()
436
2
        << "}";
437
2
    return out.str();
438
2
}
439
440
1
std::string table_filter_debug_string(const TableFilter& filter) {
441
1
    std::ostringstream out;
442
1
    out << "TableFilter{conjunct=" << expr_context_debug_string(filter.conjunct)
443
1
        << ", global_indices="
444
1
        << join_table_reader_debug_strings(
445
1
                   filter.global_indices,
446
1
                   [](GlobalIndex global_index) { return std::to_string(global_index.value()); })
447
1
        << "}";
448
1
    return out.str();
449
1
}
450
451
4
bool contains_runtime_filter(const VExprContextSPtrs& conjuncts) {
452
4
    return std::ranges::any_of(conjuncts, [](const auto& conjunct) {
453
4
        return conjunct != nullptr && conjunct->root() != nullptr &&
454
4
               conjunct->root()->is_rf_wrapper();
455
4
    });
456
4
}
457
458
283k
void collect_global_indices(const VExprSPtr& expr, std::set<GlobalIndex>* global_indices) {
459
283k
    if (expr == nullptr) {
460
0
        return;
461
0
    }
462
283k
    if (expr->is_rf_wrapper()) {
463
        // RuntimeFilterExpr wraps a real predicate expression but its own thrift node can still
464
        // look like SLOT_REF. Collect indices from the wrapped predicate; do not cast the wrapper
465
        // itself to VSlotRef.
466
9.08k
        collect_global_indices(expr->get_impl(), global_indices);
467
9.08k
        return;
468
9.08k
    }
469
274k
    if (expr->is_slot_ref()) {
470
90.3k
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
471
90.3k
        DORIS_CHECK(slot_ref->column_id() >= 0);
472
90.3k
        global_indices->insert(GlobalIndex(cast_set<size_t>(slot_ref->column_id())));
473
90.3k
    }
474
274k
    for (const auto& child : expr->children()) {
475
186k
        collect_global_indices(child, global_indices);
476
186k
    }
477
274k
}
478
479
Status build_table_filters_from_conjunct(const VExprContextSPtr& conjunct, RuntimeState* state,
480
82.4k
                                         std::vector<TableFilter>* table_filters) {
481
82.4k
    if (conjunct == nullptr) {
482
0
        return Status::OK();
483
0
    }
484
82.4k
    std::set<GlobalIndex> global_indices;
485
82.4k
    collect_global_indices(conjunct->root(), &global_indices);
486
82.6k
    if (!global_indices.empty()) {
487
82.6k
        TableFilter table_filter;
488
82.6k
        VExprSPtr filter_root;
489
82.6k
        RETURN_IF_ERROR(clone_table_expr_tree(conjunct->root(), &filter_root));
490
82.6k
        table_filter.conjunct = VExprContext::create_shared(std::move(filter_root));
491
83.9k
        for (const auto global_index : global_indices) {
492
83.9k
            table_filter.global_indices.push_back(global_index);
493
83.9k
        }
494
82.6k
        table_filters->push_back(std::move(table_filter));
495
82.6k
    }
496
82.4k
    return Status::OK();
497
82.4k
}
498
499
Status parse_deletion_vector(const char* buf, size_t buffer_size, DeleteFileDesc::Format format,
500
2.28k
                             DeletionVector* deletion_vector) {
501
2.28k
    DORIS_CHECK(buf != nullptr);
502
2.28k
    DORIS_CHECK(deletion_vector != nullptr);
503
2.28k
    DORIS_CHECK(format == DeleteFileDesc::Format::PAIMON ||
504
2.28k
                format == DeleteFileDesc::Format::ICEBERG);
505
506
2.28k
    if (format == DeleteFileDesc::Format::PAIMON) {
507
237
        RETURN_IF_ERROR(decode_paimon_deletion_vector_buffer(buf, buffer_size, deletion_vector));
508
237
        return Status::OK();
509
237
    }
510
511
2.05k
    return decode_iceberg_deletion_vector_buffer(buf, buffer_size, deletion_vector);
512
2.28k
}
513
514
} // namespace
515
516
std::shared_ptr<io::FileSystemProperties> create_system_properties(
517
58.9k
        const TFileScanRangeParams* scan_params) {
518
58.9k
    auto system_properties = std::make_shared<io::FileSystemProperties>();
519
58.9k
    if (scan_params == nullptr || !scan_params->__isset.file_type) {
520
7.21k
        system_properties->system_type = TFileType::FILE_LOCAL;
521
7.21k
        return system_properties;
522
7.21k
    }
523
51.7k
    system_properties->system_type = scan_params->file_type;
524
51.7k
    system_properties->properties = scan_params->properties;
525
51.7k
    system_properties->hdfs_params = scan_params->hdfs_params;
526
51.7k
    if (scan_params->__isset.broker_addresses) {
527
0
        system_properties->broker_addresses.assign(scan_params->broker_addresses.begin(),
528
0
                                                   scan_params->broker_addresses.end());
529
0
    }
530
51.7k
    return system_properties;
531
58.9k
}
532
533
12
std::string TableReader::debug_string() const {
534
12
    std::ostringstream out;
535
12
    out << "TableReader{format=" << file_format_to_string(_format)
536
12
        << ", push_down_agg_type=" << push_down_agg_to_string(_push_down_agg_type)
537
12
        << ", aggregate_pushdown_tried=" << _aggregate_pushdown_tried
538
12
        << ", has_current_reader=" << (_data_reader.reader != nullptr)
539
12
        << ", has_current_task=" << (_current_task != nullptr)
540
12
        << ", current_file=" << current_file_debug_string(_current_task)
541
12
        << ", has_delete_rows=" << (_delete_rows != nullptr)
542
12
        << ", delete_row_count=" << (_delete_rows == nullptr ? 0 : _delete_rows->size())
543
12
        << ", has_deletion_vector=" << (_deletion_vector != nullptr)
544
12
        << ", deletion_vector_cardinality="
545
12
        << (_deletion_vector == nullptr ? 0 : _deletion_vector->cardinality())
546
12
        << ", has_system_properties=" << (_system_properties != nullptr) << ", system_type="
547
12
        << (_system_properties == nullptr ? static_cast<int>(TFileType::FILE_LOCAL)
548
12
                                          : static_cast<int>(_system_properties->system_type))
549
12
        << ", has_scan_params=" << (_scan_params != nullptr)
550
12
        << ", has_io_ctx=" << (_io_ctx != nullptr)
551
12
        << ", has_runtime_state=" << (_runtime_state != nullptr)
552
12
        << ", has_scanner_profile=" << (_scanner_profile != nullptr)
553
12
        << ", mapper_options=" << _mapper_options.debug_string() << ", projected_columns="
554
12
        << join_table_reader_debug_strings(
555
12
                   _projected_columns,
556
12
                   [](const ColumnDefinition& column) { return column.debug_string(); })
557
12
        << ", partition_values=" << partition_values_debug_string(_partition_values)
558
12
        << ", table_filters="
559
12
        << join_table_reader_debug_strings(
560
12
                   _table_filters,
561
12
                   [](const TableFilter& filter) { return table_filter_debug_string(filter); })
562
12
        << ", conjunct_count=" << _conjuncts.size() << ", conjuncts="
563
12
        << join_table_reader_debug_strings(_conjuncts,
564
12
                                           [](const VExprContextSPtr& conjunct) {
565
1
                                               return expr_context_debug_string(conjunct);
566
1
                                           })
567
12
        << ", file_schema="
568
12
        << join_table_reader_debug_strings(
569
12
                   _data_reader.file_schema,
570
12
                   [](const ColumnDefinition& field) { return field.debug_string(); })
571
12
        << ", file_block_layout="
572
12
        << join_table_reader_debug_strings(
573
12
                   _data_reader.file_block_layout,
574
12
                   [](const FileBlockColumn& column) {
575
2
                       std::ostringstream column_out;
576
2
                       column_out << "FileBlockColumn{file_column_id=" << column.file_column_id
577
2
                                  << ", name=" << column.name << ", type="
578
2
                                  << (column.type == nullptr ? "null" : column.type->get_name())
579
2
                                  << "}";
580
2
                       return column_out.str();
581
2
                   })
582
12
        << ", block_template_columns=" << _data_reader.block_template.columns()
583
12
        << ", column_mapper="
584
12
        << (_data_reader.column_mapper == nullptr ? "null"
585
12
                                                  : _data_reader.column_mapper->debug_string())
586
12
        << "}";
587
12
    return out.str();
588
12
}
589
590
Status TableReader::annotate_projected_column(const TFileScanSlotInfo& slot_info,
591
                                              ProjectedColumnBuildContext* context,
592
290k
                                              ColumnDefinition* column) const {
593
290k
    (void)slot_info;
594
290k
    DORIS_CHECK(context != nullptr);
595
290k
    DORIS_CHECK(column != nullptr);
596
290k
    context->schema_column.reset();
597
290k
    const auto* schema_field = find_external_root_field(context->scan_params, *column);
598
290k
    if (schema_field == nullptr) {
599
181k
        return Status::OK();
600
181k
    }
601
109k
    context->schema_column = build_schema_column_from_external_field(*schema_field, column->type);
602
109k
    const bool use_current_semantics = supports_iceberg_scan_semantics_v1(context->scan_params);
603
109k
    if (!use_current_semantics) {
604
        // IDs and encoded defaults predate the result-changing semantics. Strip only the new
605
        // default channel so an old-FE plan keeps the same generic root/nested values on every BE.
606
30.6k
        clear_initial_default_metadata(&*context->schema_column);
607
30.6k
    }
608
109k
    column->identifier = context->schema_column->identifier;
609
109k
    column->name_mapping = context->schema_column->name_mapping;
610
109k
    column->has_name_mapping = context->schema_column->has_name_mapping;
611
    // Projected roots already carry a generic FE default expression, but Iceberg binary defaults
612
    // need the raw Base64 marker so missing-file materialization can decode rather than copy text.
613
109k
    column->initial_default_value = context->schema_column->initial_default_value;
614
109k
    column->initial_default_value_is_base64 =
615
109k
            context->schema_column->initial_default_value_is_base64;
616
109k
    return Status::OK();
617
290k
}
618
619
std::optional<ColumnDefinition> TableReader::_find_current_table_column_by_field_id(
620
10
        int32_t field_id, DataTypePtr type) const {
621
10
    if (_scan_params == nullptr || !_scan_params->__isset.history_schema_info ||
622
10
        _scan_params->history_schema_info.empty()) {
623
4
        return std::nullopt;
624
4
    }
625
6
    const auto* schema = &_scan_params->history_schema_info.front();
626
6
    if (_scan_params->__isset.current_schema_id) {
627
6
        for (const auto& candidate_schema : _scan_params->history_schema_info) {
628
6
            if (candidate_schema.__isset.schema_id &&
629
6
                candidate_schema.schema_id == _scan_params->current_schema_id) {
630
6
                schema = &candidate_schema;
631
6
                break;
632
6
            }
633
6
        }
634
6
    }
635
6
    if (!schema->__isset.root_field || !schema->root_field.__isset.fields) {
636
0
        return std::nullopt;
637
0
    }
638
11
    for (const auto& field_ptr : schema->root_field.fields) {
639
11
        const auto* field = get_field_ptr(field_ptr);
640
11
        if (field != nullptr && field->__isset.id && field->id == field_id) {
641
6
            return build_schema_column_from_external_field(*field, std::move(type));
642
6
        }
643
11
    }
644
0
    return std::nullopt;
645
6
}
646
647
59.1k
Status TableReader::init(TableReadOptions&& options) {
648
59.1k
    _scanner_profile = options.scanner_profile;
649
59.1k
    if (_scanner_profile != nullptr) {
650
59.0k
        const auto hierarchy = file_scan_profile::ensure_hierarchy(_scanner_profile);
651
59.0k
        static const char* table_profile = file_scan_profile::TABLE_READER;
652
59.0k
        static const char* file_reader_profile = file_scan_profile::FILE_READER;
653
59.0k
        _profile.total_timer = hierarchy.table_reader;
654
59.0k
        _profile.file_reader_total_timer = hierarchy.file_reader;
655
59.0k
        _profile.init_timer =
656
59.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "InitTime", table_profile, 1);
657
59.0k
        _profile.num_delete_files = ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "NumDeleteFiles",
658
59.0k
                                                                 TUnit::UNIT, table_profile, 1);
659
59.0k
        _profile.num_delete_rows = ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "NumDeleteRows",
660
59.0k
                                                                TUnit::UNIT, table_profile, 1);
661
59.0k
        _profile.parse_delete_file_time = ADD_CHILD_TIMER_WITH_LEVEL(
662
59.0k
                _scanner_profile, "ParseDeleteFileTime", table_profile, 1);
663
59.0k
        _profile.decoded_dv_cache_hit_count =
664
59.0k
                ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "DeletionVectorDecodedCacheHitCount",
665
59.0k
                                             TUnit::UNIT, table_profile, 1);
666
59.0k
        _profile.decoded_dv_cache_miss_count = ADD_CHILD_COUNTER_WITH_LEVEL(
667
59.0k
                _scanner_profile, "DeletionVectorDecodedCacheMissCount", TUnit::UNIT, table_profile,
668
59.0k
                1);
669
59.0k
        _profile.dv_file_cache_hit_count = ADD_CHILD_COUNTER_WITH_LEVEL(
670
59.0k
                _scanner_profile, "DeletionVectorFileCacheHitCount", TUnit::UNIT, table_profile, 1);
671
59.0k
        _profile.dv_file_cache_miss_count =
672
59.0k
                ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "DeletionVectorFileCacheMissCount",
673
59.0k
                                             TUnit::UNIT, table_profile, 1);
674
59.0k
        _profile.dv_file_cache_peer_read_count = ADD_CHILD_COUNTER_WITH_LEVEL(
675
59.0k
                _scanner_profile, "DeletionVectorFileCachePeerReadCount", TUnit::UNIT,
676
59.0k
                table_profile, 1);
677
59.0k
        _profile.exec_timer =
678
59.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "GetBlockTime", table_profile, 1);
679
59.0k
        _profile.prepare_split_timer =
680
59.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "PrepareSplitTime", table_profile, 1);
681
59.0k
        _profile.finalize_timer =
682
59.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "FinalizeBlockTime", table_profile, 1);
683
59.0k
        _profile.create_reader_timer =
684
59.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "CreateReaderTime", table_profile, 1);
685
59.0k
        _profile.pushdown_agg_timer =
686
59.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "PushDownAggTime", table_profile, 1);
687
59.0k
        _profile.open_reader_timer =
688
59.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "OpenReaderTime", table_profile, 1);
689
59.0k
        _profile.runtime_filter_partition_prune_timer = ADD_CHILD_TIMER_WITH_LEVEL(
690
59.0k
                _scanner_profile, "FileScannerRuntimeFilterPartitionPruningTime", table_profile, 1);
691
59.0k
        _profile.runtime_filter_partition_pruned_range_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
692
59.0k
                _scanner_profile, "RuntimeFilterPartitionPrunedRangeNum", TUnit::UNIT,
693
59.0k
                table_profile, 1);
694
59.0k
        _profile.close_timer =
695
59.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "CloseTime", table_profile, 1);
696
        // Lifecycle timer names remain globally unique because RuntimeProfile's visual hierarchy
697
        // does not namespace counters that share the same display parent.
698
59.0k
        _profile.file_reader_init_timer = ADD_CHILD_TIMER_WITH_LEVEL(
699
59.0k
                _scanner_profile, "FileReaderInitTime", file_reader_profile, 1);
700
59.0k
        _profile.file_reader_schema_timer = ADD_CHILD_TIMER_WITH_LEVEL(
701
59.0k
                _scanner_profile, "FileReaderGetSchemaTime", file_reader_profile, 1);
702
59.0k
        _profile.file_reader_mapper_timer = ADD_CHILD_TIMER_WITH_LEVEL(
703
59.0k
                _scanner_profile, "FileReaderCreateColumnMapperTime", file_reader_profile, 1);
704
59.0k
        _profile.file_reader_open_timer = ADD_CHILD_TIMER_WITH_LEVEL(
705
59.0k
                _scanner_profile, "FileReaderOpenTime", file_reader_profile, 1);
706
59.0k
        _profile.file_reader_get_block_timer = ADD_CHILD_TIMER_WITH_LEVEL(
707
59.0k
                _scanner_profile, "FileReaderGetBlockTime", file_reader_profile, 1);
708
59.0k
        _profile.file_reader_aggregate_timer = ADD_CHILD_TIMER_WITH_LEVEL(
709
59.0k
                _scanner_profile, "FileReaderAggregatePushDownTime", file_reader_profile, 1);
710
59.0k
        _profile.file_reader_close_timer = ADD_CHILD_TIMER_WITH_LEVEL(
711
59.0k
                _scanner_profile, "FileReaderCloseTime", file_reader_profile, 1);
712
59.0k
    }
713
    // Establish lifecycle timers before consuming options or constructing filesystem properties;
714
    // placing these scopes at the tail records only scope teardown and hides expensive init work.
715
59.1k
    SCOPED_TIMER(_profile.total_timer);
716
59.1k
    SCOPED_TIMER(_profile.init_timer);
717
59.1k
    _scan_params = options.scan_params;
718
59.1k
    _format = options.format;
719
59.1k
    _io_ctx = options.io_ctx;
720
59.1k
    _runtime_state = options.runtime_state;
721
59.1k
    _file_slot_descs = options.file_slot_descs;
722
59.1k
    _push_down_agg_type = options.push_down_agg_type;
723
59.1k
    _push_down_count_columns = options.push_down_count_columns;
724
59.1k
    _initial_condition_cache_digest = options.condition_cache_digest;
725
59.1k
    _condition_cache_digest = _initial_condition_cache_digest;
726
59.1k
    _projected_columns = std::move(options.projected_columns);
727
59.1k
    if (supports_iceberg_scan_semantics_v1(_scan_params)) {
728
79.4k
        for (auto& projected_column : _projected_columns) {
729
79.4k
            const auto* schema_field = find_external_root_field(_scan_params, projected_column);
730
79.4k
            if (schema_field != nullptr) {
731
79.1k
                attach_full_schema_identity(
732
79.1k
                        &projected_column,
733
79.1k
                        build_schema_identity_from_external_field(*schema_field));
734
79.1k
            }
735
79.4k
        }
736
21.6k
    }
737
59.1k
    _system_properties = create_system_properties(_scan_params);
738
59.1k
    _mapper_options.mode = TableColumnMappingMode::BY_NAME;
739
59.1k
    _conjuncts = std::move(options.conjuncts);
740
59.1k
    return Status::OK();
741
59.1k
}
742
743
122k
Status TableReader::_build_table_filters_from_conjuncts() {
744
122k
    _table_filters.clear();
745
122k
    _constant_pruning_safe_filter_count = 0;
746
122k
    bool in_safe_prefix = true;
747
122k
    for (const auto& conjunct : _conjuncts) {
748
82.4k
        DORIS_CHECK(conjunct != nullptr);
749
82.4k
        DORIS_CHECK(conjunct->root() != nullptr);
750
        // `_table_filters` omits expressions without slot references, but such an expression still
751
        // occupies a position in the row-level conjunct order. Record how many localized filters
752
        // precede the first unsafe original conjunct so constant pruning cannot jump over a
753
        // slotless non-deterministic/error-preserving barrier. Unsafe predicates remain solely on
754
        // Scanner's original row-level path because localizing a clone would execute their state
755
        // twice with independent state.
756
82.4k
        if (in_safe_prefix && !_is_safe_to_pre_execute(conjunct)) {
757
10.1k
            in_safe_prefix = false;
758
10.1k
        }
759
82.4k
        RETURN_IF_ERROR(
760
82.4k
                build_table_filters_from_conjunct(conjunct, _runtime_state, &_table_filters));
761
82.4k
        if (in_safe_prefix) {
762
70.5k
            _constant_pruning_safe_filter_count = _table_filters.size();
763
70.5k
        }
764
82.4k
    }
765
122k
    return Status::OK();
766
122k
}
767
768
121k
Status TableReader::_open_local_filter_exprs(const FileScanRequest& file_request) {
769
121k
    RowDescriptor row_desc;
770
121k
    for (const auto& conjunct : file_request.conjuncts) {
771
71.8k
        RETURN_IF_ERROR(conjunct->prepare(_runtime_state, row_desc));
772
71.8k
        RETURN_IF_ERROR(conjunct->open(_runtime_state));
773
71.8k
    }
774
121k
    for (const auto& delete_conjunct : file_request.delete_conjuncts) {
775
31.0k
        RETURN_IF_ERROR(delete_conjunct->prepare(_runtime_state, row_desc));
776
31.0k
        RETURN_IF_ERROR(delete_conjunct->open(_runtime_state));
777
31.0k
    }
778
121k
    return Status::OK();
779
121k
}
780
781
121k
bool TableReader::_should_enable_condition_cache(const FileScanRequest& file_request) const {
782
121k
    if (_condition_cache_digest == 0 || _push_down_agg_type == TPushAggOp::type::COUNT ||
783
121k
        _current_file_description == std::nullopt || _data_reader.reader == nullptr) {
784
18.6k
        return false;
785
18.6k
    }
786
    // Condition cache is populated by file readers after evaluating file-local row-level
787
    // conjuncts. Metadata pruning can skip row groups/pages, but it does not produce a per-row
788
    // survivor bitmap that can safely populate the cache.
789
102k
    if (file_request.conjuncts.empty()) {
790
59.1k
        return false;
791
59.1k
    }
792
    // Delete files/deletion vectors are table-format state. They may change independently of the
793
    // data file path/mtime/size used by the external cache key, so caching their result can become
794
    // stale. Keep delete filtering enabled, but do not read or write condition cache.
795
43.8k
    if (_delete_rows != nullptr || _deletion_vector != nullptr ||
796
43.8k
        !file_request.delete_conjuncts.empty()) {
797
18.6k
        return false;
798
18.6k
    }
799
    // Only scanner-driven splits provide a digest rebuilt from the exact RF snapshot. Keep the
800
    // conservative behavior for standalone TableReader callers: their initial digest may describe
801
    // only static predicate P and must not store P AND RF under that key.
802
25.1k
    return _condition_cache_digest_covers_current_split ||
803
25.1k
           !contains_runtime_filter(file_request.conjuncts);
804
43.8k
}
805
806
121k
Status TableReader::_init_reader_condition_cache(const FileScanRequest& file_request) {
807
121k
    _condition_cache = nullptr;
808
121k
    _condition_cache_ctx = nullptr;
809
121k
    if (!_should_enable_condition_cache(file_request)) {
810
96.2k
        return Status::OK();
811
96.2k
    }
812
813
25.5k
    auto* cache = segment_v2::ConditionCache::instance();
814
25.5k
    if (cache == nullptr) {
815
0
        return Status::OK();
816
0
    }
817
25.5k
    const auto& file = *_current_file_description;
818
25.5k
    _condition_cache_key = segment_v2::ConditionCache::ExternalCacheKey(
819
25.5k
            file.path, file.mtime, file.file_size, _condition_cache_digest, file.range_start_offset,
820
25.5k
            file.range_size,
821
25.5k
            segment_v2::ConditionCache::ExternalCacheKey::BASE_GRANULE_AWARE_VERSION);
822
823
25.5k
    segment_v2::ConditionCacheHandle handle;
824
25.5k
    const bool condition_cache_hit = cache->lookup(_condition_cache_key, &handle);
825
25.5k
    if (condition_cache_hit) {
826
3.81k
        _condition_cache = handle.get_filter_result();
827
3.81k
        ++_condition_cache_hit_count;
828
21.7k
    } else {
829
21.7k
        const int64_t total_rows = _data_reader.reader->get_total_rows();
830
21.7k
        if (total_rows <= 0) {
831
17.0k
            return Status::OK();
832
17.0k
        }
833
        // Add one guard granule for split ranges that start in the middle of a granule. A guard
834
        // false bit beyond the real range never overlaps real rows, but avoids boundary overflow
835
        // when a reader marks the last partial granule.
836
4.68k
        const size_t num_granules = (total_rows + ConditionCacheContext::GRANULE_SIZE - 1) /
837
4.68k
                                    ConditionCacheContext::GRANULE_SIZE;
838
4.68k
        _condition_cache = std::make_shared<std::vector<bool>>(num_granules + 1, false);
839
4.68k
    }
840
841
8.63k
    if (_condition_cache != nullptr) {
842
8.63k
        _condition_cache_ctx = std::make_shared<ConditionCacheContext>();
843
8.63k
        _condition_cache_ctx->is_hit = condition_cache_hit;
844
8.63k
        _condition_cache_ctx->filter_result = _condition_cache;
845
8.63k
        _condition_cache_ctx->num_granules = _condition_cache->size();
846
8.63k
        if (condition_cache_hit) {
847
3.81k
            _condition_cache_ctx->base_granule = handle.get_base_granule();
848
3.81k
        }
849
8.63k
        _data_reader.reader->set_condition_cache_context(_condition_cache_ctx);
850
8.63k
    }
851
8.49k
    return Status::OK();
852
25.5k
}
853
854
122k
void TableReader::_finalize_reader_condition_cache() {
855
122k
    if (_condition_cache_ctx == nullptr || _condition_cache_ctx->is_hit) {
856
117k
        _condition_cache = nullptr;
857
117k
        _condition_cache_ctx = nullptr;
858
117k
        return;
859
117k
    }
860
    // LIMIT or scanner cancellation may close a reader before all selected row ranges are visited.
861
    // Unvisited granules remain false in a MISS bitmap, so inserting a partial bitmap would make a
862
    // later HIT skip valid rows. Only publish cache entries after the physical reader reaches EOF.
863
4.77k
    if (!_current_reader_reached_eof) {
864
80
        _condition_cache = nullptr;
865
80
        _condition_cache_ctx = nullptr;
866
80
        return;
867
80
    }
868
4.69k
    DORIS_CHECK(_condition_cache_ctx->num_granules <= _condition_cache->size());
869
4.69k
    _condition_cache->resize(_condition_cache_ctx->num_granules);
870
4.69k
    segment_v2::ConditionCache::instance()->insert(
871
4.69k
            _condition_cache_key, std::move(_condition_cache), _condition_cache_ctx->base_granule);
872
4.69k
    _condition_cache = nullptr;
873
4.69k
    _condition_cache_ctx = nullptr;
874
4.69k
}
875
876
240k
Status TableReader::create_next_reader(bool* eos) {
877
240k
    SCOPED_TIMER(_profile.create_reader_timer);
878
240k
    DCHECK(_data_reader.reader == nullptr);
879
240k
    if (_current_task == nullptr) {
880
119k
        *eos = true;
881
119k
        return Status::OK();
882
119k
    }
883
884
120k
    RETURN_IF_ERROR(create_file_reader(&_data_reader.reader));
885
120k
    DORIS_CHECK(_data_reader.reader != nullptr);
886
121k
    if (_batch_size > 0) {
887
121k
        _data_reader.reader->set_batch_size(_batch_size);
888
121k
    }
889
120k
    Status st;
890
120k
    {
891
120k
        SCOPED_TIMER(_profile.file_reader_total_timer);
892
120k
        SCOPED_TIMER(_profile.file_reader_init_timer);
893
120k
        st = _data_reader.reader->init(_runtime_state);
894
120k
    }
895
120k
    if (!st.ok()) {
896
3
        if (_io_ctx != nullptr && _io_ctx->should_stop && st.is<ErrorCode::END_OF_FILE>()) {
897
0
            *eos = true;
898
0
            _data_reader.reader.reset();
899
0
            return Status::OK();
900
0
        }
901
3
        return st;
902
3
    }
903
120k
    st = open_reader();
904
120k
    if (!st.ok()) {
905
14
        if (_io_ctx != nullptr && _io_ctx->should_stop && st.is<ErrorCode::END_OF_FILE>()) {
906
0
            *eos = true;
907
0
            _data_reader.reader.reset();
908
0
            return Status::OK();
909
0
        }
910
14
        return st;
911
14
    }
912
120k
    if (_data_reader.reader == nullptr) {
913
693
        *eos = _current_task == nullptr;
914
693
        return Status::OK();
915
693
    }
916
120k
    *eos = false;
917
120k
    return Status::OK();
918
120k
}
919
920
121k
Status TableReader::create_file_reader(std::unique_ptr<FileReader>* reader) {
921
121k
    DORIS_CHECK(reader != nullptr);
922
121k
    const bool enable_mapping_timestamp_tz = _scan_params != nullptr &&
923
121k
                                             _scan_params->__isset.enable_mapping_timestamp_tz &&
924
122k
                                             _scan_params->enable_mapping_timestamp_tz;
925
121k
    const bool enable_mapping_varbinary = _scan_params != nullptr &&
926
122k
                                          _scan_params->__isset.enable_mapping_varbinary &&
927
122k
                                          _scan_params->enable_mapping_varbinary;
928
121k
    if (_format == FileFormat::PARQUET) {
929
        // V2 must honor the scan contract directly; otherwise Hive STRING columns backed by an
930
        // unannotated BYTE_ARRAY are silently exposed as VARBINARY and predicate bytes no longer
931
        // match the table type.
932
82.8k
        *reader = std::make_unique<format::parquet::ParquetReader>(
933
82.8k
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
934
82.8k
                _global_rowid_context, enable_mapping_timestamp_tz, enable_mapping_varbinary);
935
82.8k
        return Status::OK();
936
82.8k
    }
937
38.5k
    if (_format == FileFormat::ORC) {
938
32.8k
        *reader = std::make_unique<format::orc::OrcReader>(
939
32.8k
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
940
32.8k
                _global_rowid_context, enable_mapping_timestamp_tz);
941
32.8k
        return Status::OK();
942
32.8k
    }
943
5.68k
    if (_format == FileFormat::CSV) {
944
820
        if (_file_slot_descs == nullptr) {
945
0
            return Status::InvalidArgument("CSV reader requires file slot descriptors");
946
0
        }
947
        // CSV has no embedded schema. TableReader owns table-level mapping, while CsvReader needs
948
        // only the physical file slots plus scan text parameters to build a file-local schema.
949
        // Non-file columns such as partitions/defaults/virtual row ids are intentionally excluded
950
        // from `_file_slot_descs` and are materialized during finalize_chunk().
951
820
        *reader = std::make_unique<format::csv::CsvReader>(
952
820
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
953
820
                _scan_params, *_file_slot_descs, _current_range_compress_type,
954
820
                _current_range_load_id);
955
820
        return Status::OK();
956
820
    }
957
4.86k
    if (_format == FileFormat::TEXT) {
958
4.68k
        if (_file_slot_descs == nullptr) {
959
0
            return Status::InvalidArgument("Text reader requires file slot descriptors");
960
0
        }
961
        // Text files have no embedded schema. As with CSV, TableReader handles table-level mapping
962
        // and only passes physical file slots to the v2 TextReader.
963
4.68k
        *reader = std::make_unique<format::text::TextReader>(
964
4.68k
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
965
4.68k
                _scan_params, *_file_slot_descs, _current_range_compress_type,
966
4.68k
                _current_range_load_id);
967
4.68k
        return Status::OK();
968
4.68k
    }
969
581
    if (_format == FileFormat::JSON) {
970
581
        if (_file_slot_descs == nullptr) {
971
0
            return Status::InvalidArgument("JSON reader requires file slot descriptors");
972
0
        }
973
581
        *reader = std::make_unique<format::json::JsonReader>(
974
581
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
975
581
                _scan_params, _current_file_range_desc, *_file_slot_descs,
976
581
                _current_range_compress_type, _current_range_load_id);
977
581
        return Status::OK();
978
581
    }
979
18.4E
    if (_format == FileFormat::NATIVE) {
980
0
        *reader = std::make_unique<format::native::NativeReader>(
981
0
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile);
982
0
        return Status::OK();
983
0
    }
984
18.4E
    return Status::NotSupported("TableReader does not support file format {}",
985
18.4E
                                file_format_to_string(_format));
986
18.4E
}
987
988
127k
std::unique_ptr<io::FileDescription> create_file_description(const TFileRangeDesc& range) {
989
127k
    auto file_description = std::make_unique<io::FileDescription>();
990
127k
    file_description->path = range.path;
991
18.4E
    file_description->file_size = range.__isset.file_size ? range.file_size : -1;
992
18.4E
    file_description->mtime = range.__isset.modification_time ? range.modification_time : 0;
993
18.4E
    file_description->range_start_offset = range.__isset.start_offset ? range.start_offset : 0;
994
18.4E
    file_description->range_size = range.__isset.size ? range.size : -1;
995
127k
    if (range.__isset.fs_name) {
996
86.2k
        file_description->fs_name = range.fs_name;
997
86.2k
    }
998
128k
    if (range.__isset.file_cache_admission) {
999
128k
        file_description->file_cache_admission = range.file_cache_admission;
1000
128k
    }
1001
127k
    return file_description;
1002
127k
}
1003
1004
128k
Status TableReader::prepare_split(const SplitReadOptions& options) {
1005
128k
    SCOPED_TIMER(_profile.total_timer);
1006
128k
    SCOPED_TIMER(_profile.prepare_split_timer);
1007
128k
    _current_split_pruned = false;
1008
128k
    _all_runtime_filters_applied_for_split = options.all_runtime_filters_applied;
1009
128k
    _condition_cache_digest_covers_current_split = options.condition_cache_digest.has_value();
1010
129k
    if (options.condition_cache_digest.has_value()) {
1011
        // The split snapshot may include RFs that arrived after TableReader::init(). Use the digest
1012
        // computed from that exact snapshot. Example: an initial P digest must not be used to store
1013
        // the bitmap for P AND late RF{7, 9}; the scanner supplies digest(P AND RF{7, 9}) here.
1014
129k
        _condition_cache_digest = *options.condition_cache_digest;
1015
18.4E
    } else {
1016
        // An explicit scanner digest is split-scoped. Restore the init-time digest when a later
1017
        // standalone split omits it instead of leaking the previous split's RF payload into its key.
1018
18.4E
        _condition_cache_digest = _initial_condition_cache_digest;
1019
18.4E
    }
1020
129k
    if (options.conjuncts.has_value()) {
1021
129k
        _conjuncts = *options.conjuncts;
1022
129k
    }
1023
    // Update to current split format to handle ORC/PARQUET files in one table.
1024
128k
    _format = options.current_split_format;
1025
128k
    _partition_values = std::move(options.partition_values);
1026
128k
    _current_task.reset();
1027
128k
    _current_file_description.reset();
1028
128k
    _current_file_range_desc = options.current_range;
1029
128k
    _current_range_compress_type = options.current_range.__isset.compress_type
1030
128k
                                           ? options.current_range.compress_type
1031
128k
                                           : TFileCompressType::UNKNOWN;
1032
128k
    _current_range_load_id = options.current_range.__isset.load_id
1033
128k
                                     ? std::make_optional(options.current_range.load_id)
1034
128k
                                     : std::nullopt;
1035
128k
    _global_rowid_context = options.global_rowid_context;
1036
128k
    _delete_rows = nullptr;
1037
128k
    _deletion_vector = nullptr;
1038
128k
    _aggregate_pushdown_tried = false;
1039
128k
    _remaining_table_level_count = -1;
1040
128k
    _remaining_file_level_count = -1;
1041
128k
    _current_split_uses_metadata_count = false;
1042
128k
    _current_reader_reached_eof = false;
1043
128k
    RETURN_IF_ERROR(_evaluate_partition_prune_conjuncts(options.partition_prune_conjuncts,
1044
128k
                                                        &_current_split_pruned));
1045
128k
    if (_current_split_pruned) {
1046
539
        COUNTER_UPDATE(_profile.runtime_filter_partition_pruned_range_counter, 1);
1047
539
        return Status::OK();
1048
539
    }
1049
128k
    _current_task = std::make_unique<ScanTask>();
1050
128k
    _current_task->data_file = create_file_description(options.current_range);
1051
128k
    _current_file_description = *_current_task->data_file;
1052
    // A table-level row count is only equivalent to scanning the split when no row predicate is
1053
    // active and no predicate can arrive later. The metadata path can return several batches for
1054
    // one split; after its first synthetic batch there is no way to recover the real rows if a
1055
    // runtime filter arrives before the next scheduler turn.
1056
    // Table-level metadata only contains the number of rows; it cannot evaluate an expression or
1057
    // the NULL state of a COUNT argument. Require the new FE's explicit empty argument list, which
1058
    // means COUNT(*)/COUNT(1). A non-empty list means COUNT(col), while nullopt comes from an old FE
1059
    // whose COUNT semantics are unknown during a BE-first rolling upgrade.
1060
128k
    if (_push_down_agg_type == TPushAggOp::type::COUNT && _push_down_count_columns.has_value() &&
1061
128k
        _push_down_count_columns->empty() && options.all_runtime_filters_applied &&
1062
128k
        _conjuncts.empty() && options.current_range.__isset.table_format_params &&
1063
128k
        options.current_range.table_format_params.__isset.table_level_row_count) {
1064
2.76k
        DORIS_CHECK(options.current_range.table_format_params.table_level_row_count >= -1);
1065
2.76k
        _remaining_table_level_count =
1066
2.76k
                options.current_range.table_format_params.table_level_row_count;
1067
2.76k
        _current_split_uses_metadata_count = _is_table_level_count_active();
1068
2.76k
    }
1069
128k
    if (_is_table_level_count_active()) {
1070
222
        return Status::OK();
1071
222
    }
1072
128k
    return _parse_delete_predicates(options);
1073
128k
}
1074
1075
Status TableReader::_evaluate_partition_prune_conjuncts(const VExprContextSPtrs& conjuncts,
1076
128k
                                                        bool* can_filter_all) {
1077
128k
    DORIS_CHECK(can_filter_all != nullptr);
1078
128k
    SCOPED_TIMER(_profile.runtime_filter_partition_prune_timer);
1079
128k
    *can_filter_all = false;
1080
128k
    if (conjuncts.empty() || _partition_values.empty()) {
1081
124k
        return Status::OK();
1082
124k
    }
1083
1084
3.96k
    VExprContextSPtrs partition_conjuncts;
1085
6.51k
    for (const auto& conjunct : conjuncts) {
1086
6.51k
        DORIS_CHECK(conjunct != nullptr);
1087
6.51k
        DORIS_CHECK(conjunct->root() != nullptr);
1088
        // Keep only the safe prefix of the original conjunct order. If an unsafe conjunct is
1089
        // skipped, a later predicate could prune the split before the unsafe one reaches its
1090
        // normal row-level evaluation point.
1091
6.51k
        if (!_is_safe_to_pre_execute(conjunct)) {
1092
175
            break;
1093
175
        }
1094
6.34k
        std::set<GlobalIndex> global_indices;
1095
6.34k
        collect_global_indices(conjunct->root(), &global_indices);
1096
6.34k
        if (global_indices.empty()) {
1097
0
            continue;
1098
0
        }
1099
6.42k
        const bool partition_only = std::ranges::all_of(global_indices, [&](GlobalIndex index) {
1100
6.42k
            if (index.value() >= _projected_columns.size()) {
1101
0
                return false;
1102
0
            }
1103
6.42k
            const auto& column = _projected_columns[index.value()];
1104
6.42k
            return column.is_partition_key &&
1105
6.42k
                   find_partition_value(column, _partition_values) != nullptr;
1106
6.42k
        });
1107
6.34k
        if (partition_only) {
1108
4.61k
            partition_conjuncts.push_back(conjunct);
1109
4.61k
        }
1110
6.34k
    }
1111
3.96k
    if (partition_conjuncts.empty()) {
1112
1.43k
        return Status::OK();
1113
1.43k
    }
1114
1115
2.53k
    Block block;
1116
2.53k
    RETURN_IF_ERROR(_build_partition_prune_block(&block));
1117
2.53k
    RowDescriptor row_desc;
1118
4.65k
    for (const auto& conjunct : partition_conjuncts) {
1119
4.65k
        RETURN_IF_ERROR(conjunct->prepare(_runtime_state, row_desc));
1120
4.65k
        RETURN_IF_ERROR(conjunct->open(_runtime_state));
1121
4.65k
    }
1122
2.53k
    IColumn::Filter result_filter(block.rows(), 1);
1123
2.53k
    return VExprContext::execute_conjuncts(partition_conjuncts, nullptr, &block, &result_filter,
1124
2.53k
                                           can_filter_all);
1125
2.53k
}
1126
1127
157k
bool TableReader::_is_safe_to_pre_execute(const VExprContextSPtr& conjunct) {
1128
157k
    DORIS_CHECK(conjunct != nullptr);
1129
157k
    DORIS_CHECK(conjunct->root() != nullptr);
1130
157k
    const auto root = conjunct->root();
1131
157k
    const auto impl = root->get_impl();
1132
157k
    const auto predicate = impl != nullptr ? impl : root;
1133
    // Split pruning evaluates a predicate once before any file rows are read. Reordering
1134
    // non-deterministic or error-preserving expressions can change their row-level semantics,
1135
    // even when every referenced slot is a partition column or maps to a constant entry.
1136
157k
    return predicate->is_safe_to_execute_on_selected_rows();
1137
157k
}
1138
1139
3.31k
Status TableReader::_build_partition_prune_block(Block* block) const {
1140
3.31k
    DORIS_CHECK(block != nullptr);
1141
3.31k
    DORIS_CHECK(!_projected_columns.empty());
1142
3.31k
    block->clear();
1143
8.65k
    for (const auto& column : _projected_columns) {
1144
8.65k
        DORIS_CHECK(column.type != nullptr);
1145
8.65k
        ColumnPtr value_column = column.type->create_column_const_with_default_value(1);
1146
8.65k
        if (column.is_partition_key) {
1147
4.20k
            const auto* partition_value = find_partition_value(column, _partition_values);
1148
4.20k
            if (partition_value != nullptr) {
1149
4.20k
                value_column = column.type->create_column_const(1, *partition_value);
1150
4.20k
            }
1151
4.20k
        }
1152
8.65k
        block->insert({std::move(value_column), column.type, column.name});
1153
8.65k
    }
1154
3.31k
    return Status::OK();
1155
3.31k
}
1156
1157
127k
Status TableReader::_parse_delete_predicates(const SplitReadOptions& options) {
1158
127k
    DeleteFileDesc desc {.fs_name = options.current_range.fs_name};
1159
127k
    bool has_delete_file = false;
1160
127k
    RETURN_IF_ERROR(_parse_deletion_vector_file(options.current_range.table_format_params, &desc,
1161
127k
                                                &has_delete_file));
1162
127k
    if (has_delete_file) {
1163
25.8k
        DORIS_CHECK(options.cache != nullptr);
1164
25.8k
        Status create_status = Status::OK();
1165
1166
25.8k
        bool decoded_cache_hit = false;
1167
25.8k
        _deletion_vector = options.cache->get<DeletionVector>(
1168
25.8k
                desc.key,
1169
25.8k
                [&]() -> DeletionVector* {
1170
2.30k
                    auto deletion_vector = std::make_unique<DeletionVector>();
1171
1172
2.30k
                    DeletionVectorReader dv_reader(_runtime_state, _scanner_profile, *_scan_params,
1173
2.30k
                                                   desc, _io_ctx.get());
1174
2.30k
                    create_status = dv_reader.open();
1175
2.30k
                    if (!create_status.ok()) [[unlikely]] {
1176
0
                        return nullptr;
1177
0
                    }
1178
1179
2.30k
                    size_t bytes_read = desc.size;
1180
2.30k
                    std::vector<char> buffer(bytes_read);
1181
2.30k
                    DBUG_EXECUTE_IF("TableReader.parse_deletion_vector.io_error", {
1182
2.30k
                        create_status =
1183
2.30k
                                Status::IOError("injected format v2 deletion vector read failure");
1184
2.30k
                        return nullptr;
1185
2.30k
                    });
1186
2.29k
                    DBUG_EXECUTE_IF("TableReader.parse_deletion_vector.should_stop", {
1187
2.29k
                        create_status = Status::EndOfFile("stop read.");
1188
2.29k
                        return nullptr;
1189
2.29k
                    });
1190
2.29k
                    create_status =
1191
2.29k
                            dv_reader.read_at(desc.start_offset, {buffer.data(), bytes_read});
1192
2.29k
                    const auto& file_cache_stats = dv_reader.file_cache_statistics();
1193
2.29k
                    COUNTER_UPDATE(_profile.dv_file_cache_hit_count,
1194
2.29k
                                   file_cache_stats.num_local_io_total);
1195
2.29k
                    COUNTER_UPDATE(_profile.dv_file_cache_miss_count,
1196
2.29k
                                   file_cache_stats.num_remote_io_total);
1197
2.29k
                    COUNTER_UPDATE(_profile.dv_file_cache_peer_read_count,
1198
2.29k
                                   file_cache_stats.num_peer_io_total);
1199
2.29k
                    if (!create_status.ok()) [[unlikely]] {
1200
0
                        return nullptr;
1201
0
                    }
1202
1203
2.29k
                    const char* buf = buffer.data();
1204
2.29k
                    SCOPED_TIMER(_profile.parse_delete_file_time);
1205
2.29k
                    create_status = parse_deletion_vector(buf, bytes_read, desc.format,
1206
2.29k
                                                          deletion_vector.get());
1207
2.29k
                    if (!create_status.ok()) [[unlikely]] {
1208
1
                        return nullptr;
1209
1
                    }
1210
2.29k
                    COUNTER_UPDATE(_profile.num_delete_rows, deletion_vector->cardinality());
1211
2.29k
                    return deletion_vector.release();
1212
2.29k
                },
1213
25.8k
                &decoded_cache_hit);
1214
25.8k
        RETURN_IF_ERROR(create_status);
1215
25.8k
        COUNTER_UPDATE(decoded_cache_hit ? _profile.decoded_dv_cache_hit_count
1216
25.8k
                                         : _profile.decoded_dv_cache_miss_count,
1217
25.8k
                       1);
1218
25.8k
    }
1219
1220
127k
    return Status::OK();
1221
127k
}
1222
} // namespace doris::format