Coverage Report

Created: 2026-07-24 16:32

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