Coverage Report

Created: 2026-07-26 12:44

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