Coverage Report

Created: 2026-07-25 10:26

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