Coverage Report

Created: 2026-07-22 14:47

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