Coverage Report

Created: 2026-07-16 20:41

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/paimon_reader.h"
45
#include "format_v2/column_mapper.h"
46
#include "format_v2/delimited_text/csv_reader.h"
47
#include "format_v2/delimited_text/text_reader.h"
48
#include "format_v2/json/json_reader.h"
49
#include "format_v2/native/native_reader.h"
50
#include "format_v2/orc/orc_reader.h"
51
#include "format_v2/parquet/parquet_reader.h"
52
#include "storage/segment/condition_cache.h"
53
#include "util/debug_points.h"
54
#include "util/string_util.h"
55
56
namespace doris::format {
57
namespace {
58
59
template <typename T, typename Formatter>
60
61
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
61
61
    std::ostringstream out;
62
61
    out << "[";
63
70
    for (size_t i = 0; i < values.size(); ++i) {
64
9
        if (i > 0) {
65
3
            out << ", ";
66
3
        }
67
9
        out << formatter(values[i]);
68
9
    }
69
61
    out << "]";
70
61
    return out.str();
71
61
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_16ColumnDefinitionEZNKS0_11TableReader12debug_stringB5cxx11EvE3$_0EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
60
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
61
12
    std::ostringstream out;
62
12
    out << "[";
63
14
    for (size_t i = 0; i < values.size(); ++i) {
64
2
        if (i > 0) {
65
1
            out << ", ";
66
1
        }
67
2
        out << formatter(values[i]);
68
2
    }
69
12
    out << "]";
70
12
    return out.str();
71
12
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_11TableFilterEZNKS0_11TableReader12debug_stringB5cxx11EvE3$_1EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
60
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
61
12
    std::ostringstream out;
62
12
    out << "[";
63
13
    for (size_t i = 0; i < values.size(); ++i) {
64
1
        if (i > 0) {
65
0
            out << ", ";
66
0
        }
67
1
        out << formatter(values[i]);
68
1
    }
69
12
    out << "]";
70
12
    return out.str();
71
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
60
1
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
61
1
    std::ostringstream out;
62
1
    out << "[";
63
2
    for (size_t i = 0; i < values.size(); ++i) {
64
1
        if (i > 0) {
65
0
            out << ", ";
66
0
        }
67
1
        out << formatter(values[i]);
68
1
    }
69
1
    out << "]";
70
1
    return out.str();
71
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
60
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
61
12
    std::ostringstream out;
62
12
    out << "[";
63
13
    for (size_t i = 0; i < values.size(); ++i) {
64
1
        if (i > 0) {
65
0
            out << ", ";
66
0
        }
67
1
        out << formatter(values[i]);
68
1
    }
69
12
    out << "]";
70
12
    return out.str();
71
12
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_16ColumnDefinitionEZNKS0_11TableReader12debug_stringB5cxx11EvE3$_3EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
60
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
61
12
    std::ostringstream out;
62
12
    out << "[";
63
14
    for (size_t i = 0; i < values.size(); ++i) {
64
2
        if (i > 0) {
65
1
            out << ", ";
66
1
        }
67
2
        out << formatter(values[i]);
68
2
    }
69
12
    out << "]";
70
12
    return out.str();
71
12
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_11TableReader15FileBlockColumnEZNKS3_12debug_stringB5cxx11EvE3$_4EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
60
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
61
12
    std::ostringstream out;
62
12
    out << "[";
63
14
    for (size_t i = 0; i < values.size(); ++i) {
64
2
        if (i > 0) {
65
1
            out << ", ";
66
1
        }
67
2
        out << formatter(values[i]);
68
2
    }
69
12
    out << "]";
70
12
    return out.str();
71
12
}
72
73
12
std::string file_format_to_string(FileFormat format) {
74
12
    switch (format) {
75
5
    case FileFormat::PARQUET:
76
5
        return "PARQUET";
77
1
    case FileFormat::ORC:
78
1
        return "ORC";
79
1
    case FileFormat::CSV:
80
1
        return "CSV";
81
1
    case FileFormat::JSON:
82
1
        return "JSON";
83
1
    case FileFormat::TEXT:
84
1
        return "TEXT";
85
1
    case FileFormat::JNI:
86
1
        return "JNI";
87
1
    case FileFormat::NATIVE:
88
1
        return "NATIVE";
89
1
    case FileFormat::ARROW:
90
1
        return "ARROW";
91
12
    }
92
0
    return "UNKNOWN";
93
12
}
94
95
12
std::string push_down_agg_to_string(TPushAggOp::type op) {
96
12
    switch (op) {
97
8
    case TPushAggOp::NONE:
98
8
        return "NONE";
99
1
    case TPushAggOp::COUNT:
100
1
        return "COUNT";
101
1
    case TPushAggOp::MINMAX:
102
1
        return "MINMAX";
103
1
    case TPushAggOp::MIX:
104
1
        return "MIX";
105
1
    case TPushAggOp::COUNT_ON_INDEX:
106
1
        return "COUNT_ON_INDEX";
107
12
    }
108
0
    return "UNKNOWN";
109
12
}
110
111
12
std::string current_file_debug_string(const std::unique_ptr<ScanTask>& task) {
112
12
    if (task == nullptr || task->data_file == nullptr) {
113
11
        return "null";
114
11
    }
115
1
    const auto& file = *task->data_file;
116
1
    std::ostringstream out;
117
1
    out << "FileDescription{path=" << file.path << ", file_size=" << file.file_size
118
1
        << ", range_start_offset=" << file.range_start_offset << ", range_size=" << file.range_size
119
1
        << ", mtime=" << file.mtime << ", fs_name=" << file.fs_name
120
1
        << ", is_immutable=" << file.is_immutable
121
1
        << ", file_cache_admission=" << file.file_cache_admission << "}";
122
1
    return out.str();
123
12
}
124
125
12
std::string partition_values_debug_string(const std::map<std::string, Field>& partition_values) {
126
12
    std::ostringstream out;
127
12
    out << "{";
128
12
    size_t idx = 0;
129
12
    for (const auto& [key, _] : partition_values) {
130
1
        if (idx++ > 0) {
131
0
            out << ", ";
132
0
        }
133
1
        out << key;
134
1
    }
135
12
    out << "}";
136
12
    return out.str();
137
12
}
138
139
679k
const schema::external::TField* get_field_ptr(const schema::external::TFieldPtr& field_ptr) {
140
679k
    if (!field_ptr.__isset.field_ptr || field_ptr.field_ptr == nullptr) {
141
0
        return nullptr;
142
0
    }
143
679k
    return field_ptr.field_ptr.get();
144
679k
}
145
146
// Associates a projected column with its current-schema field (by current name, then aliases).
147
// This is the current-schema association phase, NOT legacy-file matching: it must match the field
148
// by its own current name so annotate_projected_column can copy the field id / aliases / mapping
149
// marker. Strict name-mapping resolution (no physical-name fallback) belongs only to the id-less
150
// file matching path in column_mapper (column_names_match), not here.
151
667k
bool external_field_matches_name(const schema::external::TField& field, const std::string& name) {
152
667k
    if (field.__isset.name && to_lower(field.name) == to_lower(name)) {
153
77.3k
        return true;
154
77.3k
    }
155
589k
    return field.__isset.name_mapping &&
156
589k
           std::ranges::any_of(field.name_mapping, [&](const std::string& alias) {
157
16
               return to_lower(alias) == to_lower(name);
158
16
           });
159
667k
}
160
161
DataTypePtr find_struct_child_type_by_external_field(const DataTypeStruct& struct_type,
162
20.8k
                                                     const schema::external::TField& field) {
163
36.8k
    for (size_t field_idx = 0; field_idx < struct_type.get_elements().size(); ++field_idx) {
164
34.7k
        if (external_field_matches_name(field, struct_type.get_element_name(field_idx))) {
165
18.7k
            return struct_type.get_element(field_idx);
166
18.7k
        }
167
34.7k
    }
168
2.09k
    return nullptr;
169
20.8k
}
170
171
DataTypePtr restore_current_primitive_type(const schema::external::TField& field,
172
102k
                                           DataTypePtr fallback_type) {
173
102k
    if (!field.__isset.type) {
174
8
        return fallback_type;
175
8
    }
176
102k
    const auto primitive_type = thrift_to_type(field.type.type);
177
102k
    if (is_complex_type(primitive_type)) {
178
26.3k
        return fallback_type;
179
26.3k
    }
180
    // The delete file can expose an older physical type, but initial defaults belong to the
181
    // current table field. Restore that type from FE before parsing the default and let the table
182
    // reader apply the normal promotion cast to the delete-key type.
183
76.1k
    return DataTypeFactory::instance().create_data_type(
184
76.1k
            primitive_type, false, field.type.__isset.precision ? field.type.precision : 0,
185
76.1k
            field.type.__isset.scale ? field.type.scale : 0,
186
76.1k
            field.type.__isset.len ? field.type.len : -1);
187
102k
}
188
189
ColumnDefinition build_schema_column_from_external_field(const schema::external::TField& field,
190
102k
                                                         DataTypePtr type) {
191
102k
    type = restore_current_primitive_type(field, std::move(type));
192
102k
    ColumnDefinition column {
193
102k
            .identifier = field.__isset.id ? Field::create_field<TYPE_INT>(field.id) : Field {},
194
102k
            .name = field.__isset.name ? field.name : "",
195
102k
            .name_mapping =
196
102k
                    field.__isset.name_mapping ? field.name_mapping : std::vector<std::string> {},
197
102k
            .has_name_mapping = field.__isset.name_mapping,
198
102k
            .type = std::move(type),
199
102k
            .children = {},
200
102k
            .default_expr = nullptr,
201
102k
            .initial_default_value = field.__isset.initial_default_value
202
102k
                                             ? std::make_optional(field.initial_default_value)
203
102k
                                             : std::nullopt,
204
102k
            .initial_default_value_is_base64 = field.__isset.initial_default_value_is_base64 &&
205
102k
                                               field.initial_default_value_is_base64,
206
102k
            .is_partition_key = false,
207
102k
    };
208
102k
    if (column.type == nullptr || !field.__isset.nestedField) {
209
76.1k
        return column;
210
76.1k
    }
211
212
26.3k
    const auto nested_type = remove_nullable(column.type);
213
26.3k
    switch (nested_type->get_primitive_type()) {
214
8.91k
    case TYPE_STRUCT: {
215
8.91k
        if (!field.nestedField.__isset.struct_field ||
216
8.91k
            !field.nestedField.struct_field.__isset.fields) {
217
0
            return column;
218
0
        }
219
8.91k
        const auto& struct_type = assert_cast<const DataTypeStruct&>(*nested_type);
220
20.8k
        for (const auto& child_ptr : field.nestedField.struct_field.fields) {
221
20.8k
            const auto* child_field = get_field_ptr(child_ptr);
222
20.8k
            if (child_field == nullptr || !child_field->__isset.name) {
223
0
                continue;
224
0
            }
225
20.8k
            auto child_type = find_struct_child_type_by_external_field(struct_type, *child_field);
226
20.8k
            if (child_type == nullptr) {
227
2.09k
                continue;
228
2.09k
            }
229
18.7k
            column.children.push_back(
230
18.7k
                    build_schema_column_from_external_field(*child_field, child_type));
231
18.7k
        }
232
8.91k
        break;
233
8.91k
    }
234
9.74k
    case TYPE_ARRAY: {
235
9.74k
        if (!field.nestedField.__isset.array_field ||
236
9.74k
            !field.nestedField.array_field.__isset.item_field) {
237
0
            return column;
238
0
        }
239
9.74k
        const auto* item_field = get_field_ptr(field.nestedField.array_field.item_field);
240
9.74k
        if (item_field == nullptr) {
241
0
            return column;
242
0
        }
243
9.74k
        const auto& array_type = assert_cast<const DataTypeArray&>(*nested_type);
244
9.74k
        auto child =
245
9.74k
                build_schema_column_from_external_field(*item_field, array_type.get_nested_type());
246
9.74k
        child.name = "element";
247
9.74k
        if (child.has_identifier_name()) {
248
0
            child.identifier = Field::create_field<TYPE_STRING>(child.name);
249
0
        }
250
9.74k
        column.children.push_back(std::move(child));
251
9.74k
        break;
252
9.74k
    }
253
7.66k
    case TYPE_MAP: {
254
7.66k
        if (!field.nestedField.__isset.map_field ||
255
7.66k
            !field.nestedField.map_field.__isset.key_field ||
256
7.66k
            !field.nestedField.map_field.__isset.value_field) {
257
0
            return column;
258
0
        }
259
7.66k
        const auto& map_type = assert_cast<const DataTypeMap&>(*nested_type);
260
7.66k
        const auto* key_field = get_field_ptr(field.nestedField.map_field.key_field);
261
7.66k
        if (key_field != nullptr) {
262
7.66k
            auto child =
263
7.66k
                    build_schema_column_from_external_field(*key_field, map_type.get_key_type());
264
7.66k
            child.name = "key";
265
7.66k
            if (child.has_identifier_name()) {
266
0
                child.identifier = Field::create_field<TYPE_STRING>(child.name);
267
0
            }
268
7.66k
            column.children.push_back(std::move(child));
269
7.66k
        }
270
7.66k
        const auto* value_field = get_field_ptr(field.nestedField.map_field.value_field);
271
7.66k
        if (value_field != nullptr) {
272
7.66k
            auto child = build_schema_column_from_external_field(*value_field,
273
7.66k
                                                                 map_type.get_value_type());
274
7.66k
            child.name = "value";
275
7.66k
            if (child.has_identifier_name()) {
276
0
                child.identifier = Field::create_field<TYPE_STRING>(child.name);
277
0
            }
278
7.66k
            column.children.push_back(std::move(child));
279
7.66k
        }
280
7.66k
        break;
281
7.66k
    }
282
0
    default:
283
0
        break;
284
26.3k
    }
285
26.3k
    return column;
286
26.3k
}
287
288
const schema::external::TField* find_external_root_field(const TFileScanRangeParams* params,
289
234k
                                                         const ColumnDefinition& column) {
290
234k
    if (params == nullptr || !params->__isset.history_schema_info ||
291
234k
        params->history_schema_info.empty()) {
292
175k
        return nullptr;
293
175k
    }
294
58.9k
    const auto* schema = &params->history_schema_info.front();
295
58.9k
    if (params->__isset.current_schema_id) {
296
58.9k
        for (const auto& candidate_schema : params->history_schema_info) {
297
58.9k
            if (candidate_schema.__isset.schema_id &&
298
58.9k
                candidate_schema.schema_id == params->current_schema_id) {
299
58.9k
                schema = &candidate_schema;
300
58.9k
                break;
301
58.9k
            }
302
58.9k
        }
303
58.9k
    }
304
58.9k
    if (!schema->__isset.root_field || !schema->root_field.__isset.fields) {
305
0
        return nullptr;
306
0
    }
307
634k
    for (const auto& field_ptr : schema->root_field.fields) {
308
634k
        const auto* field = get_field_ptr(field_ptr);
309
634k
        if (field == nullptr) {
310
0
            continue;
311
0
        }
312
634k
        if (external_field_matches_name(*field, column.name)) {
313
58.6k
            return field;
314
58.6k
        }
315
634k
    }
316
368
    return nullptr;
317
58.9k
}
318
319
2
std::string expr_context_debug_string(const VExprContextSPtr& context) {
320
2
    if (context == nullptr) {
321
0
        return "null";
322
0
    }
323
2
    const auto root = context->root();
324
2
    if (root == nullptr) {
325
0
        return "VExprContext{root=null}";
326
0
    }
327
2
    std::ostringstream out;
328
2
    out << "VExprContext{root_name=" << root->expr_name() << ", root_debug=" << root->debug_string()
329
2
        << "}";
330
2
    return out.str();
331
2
}
332
333
1
std::string table_filter_debug_string(const TableFilter& filter) {
334
1
    std::ostringstream out;
335
1
    out << "TableFilter{conjunct=" << expr_context_debug_string(filter.conjunct)
336
1
        << ", global_indices="
337
1
        << join_table_reader_debug_strings(
338
1
                   filter.global_indices,
339
1
                   [](GlobalIndex global_index) { return std::to_string(global_index.value()); })
340
1
        << "}";
341
1
    return out.str();
342
1
}
343
344
4
bool contains_runtime_filter(const VExprContextSPtrs& conjuncts) {
345
4
    return std::ranges::any_of(conjuncts, [](const auto& conjunct) {
346
4
        return conjunct != nullptr && conjunct->root() != nullptr &&
347
4
               conjunct->root()->is_rf_wrapper();
348
4
    });
349
4
}
350
351
146k
void collect_global_indices(const VExprSPtr& expr, std::set<GlobalIndex>* global_indices) {
352
146k
    if (expr == nullptr) {
353
0
        return;
354
0
    }
355
146k
    if (expr->is_rf_wrapper()) {
356
        // RuntimeFilterExpr wraps a real predicate expression but its own thrift node can still
357
        // look like SLOT_REF. Collect indices from the wrapped predicate; do not cast the wrapper
358
        // itself to VSlotRef.
359
5.96k
        collect_global_indices(expr->get_impl(), global_indices);
360
5.96k
        return;
361
5.96k
    }
362
140k
    if (expr->is_slot_ref()) {
363
45.3k
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
364
45.3k
        DORIS_CHECK(slot_ref->column_id() >= 0);
365
45.3k
        global_indices->insert(GlobalIndex(cast_set<size_t>(slot_ref->column_id())));
366
45.3k
    }
367
140k
    for (const auto& child : expr->children()) {
368
96.9k
        collect_global_indices(child, global_indices);
369
96.9k
    }
370
140k
}
371
372
Status build_table_filters_from_conjunct(const VExprContextSPtr& conjunct, RuntimeState* state,
373
39.8k
                                         std::vector<TableFilter>* table_filters) {
374
39.8k
    if (conjunct == nullptr) {
375
0
        return Status::OK();
376
0
    }
377
39.8k
    std::set<GlobalIndex> global_indices;
378
39.8k
    collect_global_indices(conjunct->root(), &global_indices);
379
39.8k
    if (!global_indices.empty()) {
380
39.8k
        TableFilter table_filter;
381
39.8k
        VExprSPtr filter_root;
382
39.8k
        RETURN_IF_ERROR(clone_table_expr_tree(conjunct->root(), &filter_root));
383
39.8k
        table_filter.conjunct = VExprContext::create_shared(std::move(filter_root));
384
40.9k
        for (const auto global_index : global_indices) {
385
40.9k
            table_filter.global_indices.push_back(global_index);
386
40.9k
        }
387
39.8k
        table_filters->push_back(std::move(table_filter));
388
39.8k
    }
389
39.8k
    return Status::OK();
390
39.8k
}
391
392
Status parse_deletion_vector(const char* buf, size_t buffer_size, DeleteFileDesc::Format format,
393
1.43k
                             DeletionVector* deletion_vector) {
394
1.43k
    DORIS_CHECK(buf != nullptr);
395
1.43k
    DORIS_CHECK(deletion_vector != nullptr);
396
1.43k
    DORIS_CHECK(format == DeleteFileDesc::Format::PAIMON ||
397
1.43k
                format == DeleteFileDesc::Format::ICEBERG);
398
399
1.43k
    if (format == DeleteFileDesc::Format::PAIMON) {
400
1
        RETURN_IF_ERROR(decode_paimon_deletion_vector_buffer(buf, buffer_size, deletion_vector));
401
1
        return Status::OK();
402
1
    }
403
404
1.43k
    return decode_iceberg_deletion_vector_buffer(buf, buffer_size, deletion_vector);
405
1.43k
}
406
407
} // namespace
408
409
std::shared_ptr<io::FileSystemProperties> create_system_properties(
410
39.1k
        const TFileScanRangeParams* scan_params) {
411
39.1k
    auto system_properties = std::make_shared<io::FileSystemProperties>();
412
39.1k
    if (scan_params == nullptr || !scan_params->__isset.file_type) {
413
607
        system_properties->system_type = TFileType::FILE_LOCAL;
414
607
        return system_properties;
415
607
    }
416
38.5k
    system_properties->system_type = scan_params->file_type;
417
38.5k
    system_properties->properties = scan_params->properties;
418
38.5k
    system_properties->hdfs_params = scan_params->hdfs_params;
419
38.5k
    if (scan_params->__isset.broker_addresses) {
420
0
        system_properties->broker_addresses.assign(scan_params->broker_addresses.begin(),
421
0
                                                   scan_params->broker_addresses.end());
422
0
    }
423
38.5k
    return system_properties;
424
39.1k
}
425
426
12
std::string TableReader::debug_string() const {
427
12
    std::ostringstream out;
428
12
    out << "TableReader{format=" << file_format_to_string(_format)
429
12
        << ", push_down_agg_type=" << push_down_agg_to_string(_push_down_agg_type)
430
12
        << ", aggregate_pushdown_tried=" << _aggregate_pushdown_tried
431
12
        << ", has_current_reader=" << (_data_reader.reader != nullptr)
432
12
        << ", has_current_task=" << (_current_task != nullptr)
433
12
        << ", current_file=" << current_file_debug_string(_current_task)
434
12
        << ", has_delete_rows=" << (_delete_rows != nullptr)
435
12
        << ", delete_row_count=" << (_delete_rows == nullptr ? 0 : _delete_rows->size())
436
12
        << ", has_deletion_vector=" << (_deletion_vector != nullptr)
437
12
        << ", deletion_vector_cardinality="
438
12
        << (_deletion_vector == nullptr ? 0 : _deletion_vector->cardinality())
439
12
        << ", has_system_properties=" << (_system_properties != nullptr) << ", system_type="
440
12
        << (_system_properties == nullptr ? static_cast<int>(TFileType::FILE_LOCAL)
441
12
                                          : static_cast<int>(_system_properties->system_type))
442
12
        << ", has_scan_params=" << (_scan_params != nullptr)
443
12
        << ", has_io_ctx=" << (_io_ctx != nullptr)
444
12
        << ", has_runtime_state=" << (_runtime_state != nullptr)
445
12
        << ", has_scanner_profile=" << (_scanner_profile != nullptr)
446
12
        << ", mapper_options=" << _mapper_options.debug_string() << ", projected_columns="
447
12
        << join_table_reader_debug_strings(
448
12
                   _projected_columns,
449
12
                   [](const ColumnDefinition& column) { return column.debug_string(); })
450
12
        << ", partition_values=" << partition_values_debug_string(_partition_values)
451
12
        << ", table_filters="
452
12
        << join_table_reader_debug_strings(
453
12
                   _table_filters,
454
12
                   [](const TableFilter& filter) { return table_filter_debug_string(filter); })
455
12
        << ", conjunct_count=" << _conjuncts.size() << ", conjuncts="
456
12
        << join_table_reader_debug_strings(_conjuncts,
457
12
                                           [](const VExprContextSPtr& conjunct) {
458
1
                                               return expr_context_debug_string(conjunct);
459
1
                                           })
460
12
        << ", file_schema="
461
12
        << join_table_reader_debug_strings(
462
12
                   _data_reader.file_schema,
463
12
                   [](const ColumnDefinition& field) { return field.debug_string(); })
464
12
        << ", file_block_layout="
465
12
        << join_table_reader_debug_strings(
466
12
                   _data_reader.file_block_layout,
467
12
                   [](const FileBlockColumn& column) {
468
2
                       std::ostringstream column_out;
469
2
                       column_out << "FileBlockColumn{file_column_id=" << column.file_column_id
470
2
                                  << ", name=" << column.name << ", type="
471
2
                                  << (column.type == nullptr ? "null" : column.type->get_name())
472
2
                                  << "}";
473
2
                       return column_out.str();
474
2
                   })
475
12
        << ", block_template_columns=" << _data_reader.block_template.columns()
476
12
        << ", column_mapper="
477
12
        << (_data_reader.column_mapper == nullptr ? "null"
478
12
                                                  : _data_reader.column_mapper->debug_string())
479
12
        << "}";
480
12
    return out.str();
481
12
}
482
483
Status TableReader::annotate_projected_column(const TFileScanSlotInfo& slot_info,
484
                                              ProjectedColumnBuildContext* context,
485
234k
                                              ColumnDefinition* column) const {
486
234k
    (void)slot_info;
487
234k
    DORIS_CHECK(context != nullptr);
488
234k
    DORIS_CHECK(column != nullptr);
489
234k
    context->schema_column.reset();
490
234k
    const auto* schema_field = find_external_root_field(context->scan_params, *column);
491
234k
    if (schema_field == nullptr) {
492
175k
        return Status::OK();
493
175k
    }
494
58.6k
    context->schema_column = build_schema_column_from_external_field(*schema_field, column->type);
495
58.6k
    column->identifier = context->schema_column->identifier;
496
58.6k
    column->name_mapping = context->schema_column->name_mapping;
497
58.6k
    column->has_name_mapping = context->schema_column->has_name_mapping;
498
58.6k
    return Status::OK();
499
234k
}
500
501
std::optional<ColumnDefinition> TableReader::_find_current_table_column_by_field_id(
502
9
        int32_t field_id, DataTypePtr type) const {
503
9
    if (_scan_params == nullptr || !_scan_params->__isset.history_schema_info ||
504
9
        _scan_params->history_schema_info.empty()) {
505
3
        return std::nullopt;
506
3
    }
507
6
    const auto* schema = &_scan_params->history_schema_info.front();
508
6
    if (_scan_params->__isset.current_schema_id) {
509
6
        for (const auto& candidate_schema : _scan_params->history_schema_info) {
510
6
            if (candidate_schema.__isset.schema_id &&
511
6
                candidate_schema.schema_id == _scan_params->current_schema_id) {
512
6
                schema = &candidate_schema;
513
6
                break;
514
6
            }
515
6
        }
516
6
    }
517
6
    if (!schema->__isset.root_field || !schema->root_field.__isset.fields) {
518
0
        return std::nullopt;
519
0
    }
520
11
    for (const auto& field_ptr : schema->root_field.fields) {
521
11
        const auto* field = get_field_ptr(field_ptr);
522
11
        if (field != nullptr && field->__isset.id && field->id == field_id) {
523
6
            return build_schema_column_from_external_field(*field, std::move(type));
524
6
        }
525
11
    }
526
0
    return std::nullopt;
527
6
}
528
529
39.1k
Status TableReader::init(TableReadOptions&& options) {
530
39.1k
    _scan_params = options.scan_params;
531
39.1k
    _format = options.format;
532
39.1k
    _io_ctx = options.io_ctx;
533
39.1k
    _runtime_state = options.runtime_state;
534
39.1k
    _scanner_profile = options.scanner_profile;
535
39.1k
    _file_slot_descs = options.file_slot_descs;
536
39.1k
    _push_down_agg_type = options.push_down_agg_type;
537
39.1k
    _initial_condition_cache_digest = options.condition_cache_digest;
538
39.1k
    _condition_cache_digest = _initial_condition_cache_digest;
539
39.1k
    _projected_columns = std::move(options.projected_columns);
540
39.1k
    _system_properties = create_system_properties(_scan_params);
541
39.1k
    _mapper_options.mode = TableColumnMappingMode::BY_NAME;
542
39.1k
    _conjuncts = std::move(options.conjuncts);
543
544
39.1k
    if (_scanner_profile != nullptr) {
545
39.0k
        static const char* table_profile = "TableReader";
546
39.0k
        ADD_TIMER_WITH_LEVEL(_scanner_profile, table_profile, 1);
547
39.0k
        _profile.num_delete_files = ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "NumDeleteFiles",
548
39.0k
                                                                 TUnit::UNIT, table_profile, 1);
549
39.0k
        _profile.num_delete_rows = ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "NumDeleteRows",
550
39.0k
                                                                TUnit::UNIT, table_profile, 1);
551
39.0k
        _profile.parse_delete_file_time = ADD_CHILD_TIMER_WITH_LEVEL(
552
39.0k
                _scanner_profile, "ParseDeleteFileTime", table_profile, 1);
553
39.0k
        _profile.decoded_dv_cache_hit_count =
554
39.0k
                ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "DeletionVectorDecodedCacheHitCount",
555
39.0k
                                             TUnit::UNIT, table_profile, 1);
556
39.0k
        _profile.decoded_dv_cache_miss_count = ADD_CHILD_COUNTER_WITH_LEVEL(
557
39.0k
                _scanner_profile, "DeletionVectorDecodedCacheMissCount", TUnit::UNIT, table_profile,
558
39.0k
                1);
559
39.0k
        _profile.dv_file_cache_hit_count = ADD_CHILD_COUNTER_WITH_LEVEL(
560
39.0k
                _scanner_profile, "DeletionVectorFileCacheHitCount", TUnit::UNIT, table_profile, 1);
561
39.0k
        _profile.dv_file_cache_miss_count =
562
39.0k
                ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "DeletionVectorFileCacheMissCount",
563
39.0k
                                             TUnit::UNIT, table_profile, 1);
564
39.0k
        _profile.dv_file_cache_peer_read_count = ADD_CHILD_COUNTER_WITH_LEVEL(
565
39.0k
                _scanner_profile, "DeletionVectorFileCachePeerReadCount", TUnit::UNIT,
566
39.0k
                table_profile, 1);
567
39.0k
        _profile.exec_timer =
568
39.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "GetBlockTime", table_profile, 1);
569
39.0k
        _profile.prepare_split_timer =
570
39.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "PrepareSplitTime", table_profile, 1);
571
39.0k
        _profile.finalize_timer =
572
39.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "FinalizeBlockTime", table_profile, 1);
573
39.0k
        _profile.create_reader_timer =
574
39.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "CreateReaderTime", table_profile, 1);
575
39.0k
        _profile.pushdown_agg_timer =
576
39.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "PushDownAggTime", table_profile, 1);
577
39.0k
        _profile.open_reader_timer =
578
39.0k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "OpenReaderTime", table_profile, 1);
579
39.0k
        _profile.runtime_filter_partition_prune_timer = ADD_TIMER_WITH_LEVEL(
580
39.0k
                _scanner_profile, "FileScannerRuntimeFilterPartitionPruningTime", 1);
581
39.0k
        _profile.runtime_filter_partition_pruned_range_counter = ADD_COUNTER_WITH_LEVEL(
582
39.0k
                _scanner_profile, "RuntimeFilterPartitionPrunedRangeNum", TUnit::UNIT, 1);
583
39.0k
    }
584
39.1k
    return Status::OK();
585
39.1k
}
586
587
59.9k
Status TableReader::_build_table_filters_from_conjuncts() {
588
59.9k
    _table_filters.clear();
589
59.9k
    _constant_pruning_safe_filter_count = 0;
590
59.9k
    bool in_safe_prefix = true;
591
59.9k
    for (const auto& conjunct : _conjuncts) {
592
39.8k
        DORIS_CHECK(conjunct != nullptr);
593
39.8k
        DORIS_CHECK(conjunct->root() != nullptr);
594
        // `_table_filters` omits expressions without slot references, but such an expression still
595
        // occupies a position in the row-level conjunct order. Record how many localized filters
596
        // precede the first unsafe original conjunct so constant pruning cannot jump over a
597
        // slotless non-deterministic/error-preserving barrier.
598
39.8k
        if (in_safe_prefix && !_is_safe_to_pre_execute(conjunct)) {
599
3
            in_safe_prefix = false;
600
3
        }
601
39.8k
        if (!in_safe_prefix) {
602
5
            continue;
603
5
        }
604
39.8k
        RETURN_IF_ERROR(
605
39.8k
                build_table_filters_from_conjunct(conjunct, _runtime_state, &_table_filters));
606
39.8k
        _constant_pruning_safe_filter_count = _table_filters.size();
607
39.8k
    }
608
59.9k
    return Status::OK();
609
59.9k
}
610
611
58.6k
Status TableReader::_open_local_filter_exprs(const FileScanRequest& file_request) {
612
58.6k
    RowDescriptor row_desc;
613
58.6k
    for (const auto& conjunct : file_request.conjuncts) {
614
32.6k
        RETURN_IF_ERROR(conjunct->prepare(_runtime_state, row_desc));
615
32.6k
        RETURN_IF_ERROR(conjunct->open(_runtime_state));
616
32.6k
    }
617
58.6k
    for (const auto& delete_conjunct : file_request.delete_conjuncts) {
618
8.02k
        RETURN_IF_ERROR(delete_conjunct->prepare(_runtime_state, row_desc));
619
8.02k
        RETURN_IF_ERROR(delete_conjunct->open(_runtime_state));
620
8.02k
    }
621
58.6k
    return Status::OK();
622
58.6k
}
623
624
58.7k
bool TableReader::_should_enable_condition_cache(const FileScanRequest& file_request) const {
625
58.7k
    if (_condition_cache_digest == 0 || _push_down_agg_type == TPushAggOp::type::COUNT ||
626
58.7k
        _current_file_description == std::nullopt || _data_reader.reader == nullptr) {
627
13.1k
        return false;
628
13.1k
    }
629
    // Condition cache is populated by file readers after evaluating file-local row-level
630
    // conjuncts. Metadata pruning can skip row groups/pages, but it does not produce a per-row
631
    // survivor bitmap that can safely populate the cache.
632
45.6k
    if (file_request.conjuncts.empty()) {
633
33.1k
        return false;
634
33.1k
    }
635
    // Delete files/deletion vectors are table-format state. They may change independently of the
636
    // data file path/mtime/size used by the external cache key, so caching their result can become
637
    // stale. Keep delete filtering enabled, but do not read or write condition cache.
638
12.4k
    if (_delete_rows != nullptr || _deletion_vector != nullptr ||
639
12.4k
        !file_request.delete_conjuncts.empty()) {
640
2.80k
        return false;
641
2.80k
    }
642
    // Only scanner-driven splits provide a digest rebuilt from the exact RF snapshot. Keep the
643
    // conservative behavior for standalone TableReader callers: their initial digest may describe
644
    // only static predicate P and must not store P AND RF under that key.
645
9.68k
    return _condition_cache_digest_covers_current_split ||
646
9.68k
           !contains_runtime_filter(file_request.conjuncts);
647
12.4k
}
648
649
58.6k
Status TableReader::_init_reader_condition_cache(const FileScanRequest& file_request) {
650
58.6k
    _condition_cache = nullptr;
651
58.6k
    _condition_cache_ctx = nullptr;
652
58.6k
    if (!_should_enable_condition_cache(file_request)) {
653
49.0k
        return Status::OK();
654
49.0k
    }
655
656
9.59k
    auto* cache = segment_v2::ConditionCache::instance();
657
9.59k
    if (cache == nullptr) {
658
0
        return Status::OK();
659
0
    }
660
9.59k
    const auto& file = *_current_file_description;
661
9.59k
    _condition_cache_key = segment_v2::ConditionCache::ExternalCacheKey(
662
9.59k
            file.path, file.mtime, file.file_size, _condition_cache_digest, file.range_start_offset,
663
9.59k
            file.range_size,
664
9.59k
            segment_v2::ConditionCache::ExternalCacheKey::BASE_GRANULE_AWARE_VERSION);
665
666
9.59k
    segment_v2::ConditionCacheHandle handle;
667
9.59k
    const bool condition_cache_hit = cache->lookup(_condition_cache_key, &handle);
668
9.59k
    if (condition_cache_hit) {
669
3.31k
        _condition_cache = handle.get_filter_result();
670
3.31k
        ++_condition_cache_hit_count;
671
6.28k
    } else {
672
6.28k
        const int64_t total_rows = _data_reader.reader->get_total_rows();
673
6.28k
        if (total_rows <= 0) {
674
2.41k
            return Status::OK();
675
2.41k
        }
676
        // Add one guard granule for split ranges that start in the middle of a granule. A guard
677
        // false bit beyond the real range never overlaps real rows, but avoids boundary overflow
678
        // when a reader marks the last partial granule.
679
3.87k
        const size_t num_granules = (total_rows + ConditionCacheContext::GRANULE_SIZE - 1) /
680
3.87k
                                    ConditionCacheContext::GRANULE_SIZE;
681
3.87k
        _condition_cache = std::make_shared<std::vector<bool>>(num_granules + 1, false);
682
3.87k
    }
683
684
7.22k
    if (_condition_cache != nullptr) {
685
7.22k
        _condition_cache_ctx = std::make_shared<ConditionCacheContext>();
686
7.22k
        _condition_cache_ctx->is_hit = condition_cache_hit;
687
7.22k
        _condition_cache_ctx->filter_result = _condition_cache;
688
7.22k
        _condition_cache_ctx->num_granules = _condition_cache->size();
689
7.22k
        if (condition_cache_hit) {
690
3.31k
            _condition_cache_ctx->base_granule = handle.get_base_granule();
691
3.31k
        }
692
7.22k
        _data_reader.reader->set_condition_cache_context(_condition_cache_ctx);
693
7.22k
    }
694
7.18k
    return Status::OK();
695
9.59k
}
696
697
60.0k
void TableReader::_finalize_reader_condition_cache() {
698
60.0k
    if (_condition_cache_ctx == nullptr || _condition_cache_ctx->is_hit) {
699
56.1k
        _condition_cache = nullptr;
700
56.1k
        _condition_cache_ctx = nullptr;
701
56.1k
        return;
702
56.1k
    }
703
    // LIMIT or scanner cancellation may close a reader before all selected row ranges are visited.
704
    // Unvisited granules remain false in a MISS bitmap, so inserting a partial bitmap would make a
705
    // later HIT skip valid rows. Only publish cache entries after the physical reader reaches EOF.
706
3.91k
    if (!_current_reader_reached_eof) {
707
80
        _condition_cache = nullptr;
708
80
        _condition_cache_ctx = nullptr;
709
80
        return;
710
80
    }
711
3.83k
    DORIS_CHECK(_condition_cache_ctx->num_granules <= _condition_cache->size());
712
3.83k
    _condition_cache->resize(_condition_cache_ctx->num_granules);
713
3.83k
    segment_v2::ConditionCache::instance()->insert(
714
3.83k
            _condition_cache_key, std::move(_condition_cache), _condition_cache_ctx->base_granule);
715
3.83k
    _condition_cache = nullptr;
716
3.83k
    _condition_cache_ctx = nullptr;
717
3.83k
}
718
719
118k
Status TableReader::create_next_reader(bool* eos) {
720
118k
    SCOPED_TIMER(_profile.create_reader_timer);
721
118k
    DCHECK(_data_reader.reader == nullptr);
722
118k
    if (_current_task == nullptr) {
723
58.1k
        *eos = true;
724
58.1k
        return Status::OK();
725
58.1k
    }
726
727
59.9k
    RETURN_IF_ERROR(create_file_reader(&_data_reader.reader));
728
59.9k
    DORIS_CHECK(_data_reader.reader != nullptr);
729
59.9k
    if (_batch_size > 0) {
730
57.8k
        _data_reader.reader->set_batch_size(_batch_size);
731
57.8k
    }
732
59.9k
    Status st = _data_reader.reader->init(_runtime_state);
733
59.9k
    if (!st.ok()) {
734
15
        if (_io_ctx != nullptr && _io_ctx->should_stop && st.is<ErrorCode::END_OF_FILE>()) {
735
0
            *eos = true;
736
0
            _data_reader.reader.reset();
737
0
            return Status::OK();
738
0
        }
739
15
        return st;
740
15
    }
741
59.9k
    st = open_reader();
742
59.9k
    if (!st.ok()) {
743
0
        if (_io_ctx != nullptr && _io_ctx->should_stop && st.is<ErrorCode::END_OF_FILE>()) {
744
0
            *eos = true;
745
0
            _data_reader.reader.reset();
746
0
            return Status::OK();
747
0
        }
748
0
        return st;
749
0
    }
750
59.9k
    if (_data_reader.reader == nullptr) {
751
1.24k
        *eos = _current_task == nullptr;
752
1.24k
        return Status::OK();
753
1.24k
    }
754
58.6k
    *eos = false;
755
58.6k
    return Status::OK();
756
59.9k
}
757
758
59.8k
Status TableReader::create_file_reader(std::unique_ptr<FileReader>* reader) {
759
59.8k
    DORIS_CHECK(reader != nullptr);
760
59.8k
    const bool enable_mapping_timestamp_tz = _scan_params != nullptr &&
761
59.8k
                                             _scan_params->__isset.enable_mapping_timestamp_tz &&
762
59.8k
                                             _scan_params->enable_mapping_timestamp_tz;
763
59.8k
    if (_format == FileFormat::PARQUET) {
764
31.3k
        *reader = std::make_unique<format::parquet::ParquetReader>(
765
31.3k
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
766
31.3k
                _global_rowid_context, enable_mapping_timestamp_tz);
767
31.3k
        return Status::OK();
768
31.3k
    }
769
28.4k
    if (_format == FileFormat::ORC) {
770
22.3k
        *reader = std::make_unique<format::orc::OrcReader>(
771
22.3k
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
772
22.3k
                _global_rowid_context, enable_mapping_timestamp_tz);
773
22.3k
        return Status::OK();
774
22.3k
    }
775
6.02k
    if (_format == FileFormat::CSV) {
776
773
        if (_file_slot_descs == nullptr) {
777
0
            return Status::InvalidArgument("CSV reader requires file slot descriptors");
778
0
        }
779
        // CSV has no embedded schema. TableReader owns table-level mapping, while CsvReader needs
780
        // only the physical file slots plus scan text parameters to build a file-local schema.
781
        // Non-file columns such as partitions/defaults/virtual row ids are intentionally excluded
782
        // from `_file_slot_descs` and are materialized during finalize_chunk().
783
773
        *reader = std::make_unique<format::csv::CsvReader>(
784
773
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
785
773
                _scan_params, *_file_slot_descs, _current_range_compress_type,
786
773
                _current_range_load_id);
787
773
        return Status::OK();
788
773
    }
789
5.25k
    if (_format == FileFormat::TEXT) {
790
4.75k
        if (_file_slot_descs == nullptr) {
791
0
            return Status::InvalidArgument("Text reader requires file slot descriptors");
792
0
        }
793
        // Text files have no embedded schema. As with CSV, TableReader handles table-level mapping
794
        // and only passes physical file slots to the v2 TextReader.
795
4.75k
        *reader = std::make_unique<format::text::TextReader>(
796
4.75k
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
797
4.75k
                _scan_params, *_file_slot_descs, _current_range_compress_type,
798
4.75k
                _current_range_load_id);
799
4.75k
        return Status::OK();
800
4.75k
    }
801
577
    if (_format == FileFormat::JSON) {
802
577
        if (_file_slot_descs == nullptr) {
803
0
            return Status::InvalidArgument("JSON reader requires file slot descriptors");
804
0
        }
805
577
        *reader = std::make_unique<format::json::JsonReader>(
806
577
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
807
577
                _scan_params, _current_file_range_desc, *_file_slot_descs,
808
577
                _current_range_compress_type, _current_range_load_id);
809
577
        return Status::OK();
810
577
    }
811
18.4E
    if (_format == FileFormat::NATIVE) {
812
0
        *reader = std::make_unique<format::native::NativeReader>(
813
0
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile);
814
0
        return Status::OK();
815
0
    }
816
18.4E
    return Status::NotSupported("TableReader does not support file format {}",
817
18.4E
                                file_format_to_string(_format));
818
18.4E
}
819
820
60.1k
std::unique_ptr<io::FileDescription> create_file_description(const TFileRangeDesc& range) {
821
60.1k
    auto file_description = std::make_unique<io::FileDescription>();
822
60.1k
    file_description->path = range.path;
823
18.4E
    file_description->file_size = range.__isset.file_size ? range.file_size : -1;
824
60.1k
    file_description->mtime = range.__isset.modification_time ? range.modification_time : 0;
825
60.1k
    file_description->range_start_offset = range.__isset.start_offset ? range.start_offset : 0;
826
60.1k
    file_description->range_size = range.__isset.size ? range.size : -1;
827
60.1k
    if (range.__isset.fs_name) {
828
33.2k
        file_description->fs_name = range.fs_name;
829
33.2k
    }
830
60.1k
    if (range.__isset.file_cache_admission) {
831
60.0k
        file_description->file_cache_admission = range.file_cache_admission;
832
60.0k
    }
833
60.1k
    return file_description;
834
60.1k
}
835
836
60.4k
Status TableReader::prepare_split(const SplitReadOptions& options) {
837
60.4k
    SCOPED_TIMER(_profile.prepare_split_timer);
838
60.4k
    _current_split_pruned = false;
839
60.4k
    _all_runtime_filters_applied_for_split = options.all_runtime_filters_applied;
840
60.4k
    _condition_cache_digest_covers_current_split = options.condition_cache_digest.has_value();
841
60.4k
    if (options.condition_cache_digest.has_value()) {
842
        // The split snapshot may include RFs that arrived after TableReader::init(). Use the digest
843
        // computed from that exact snapshot. Example: an initial P digest must not be used to store
844
        // the bitmap for P AND late RF{7, 9}; the scanner supplies digest(P AND RF{7, 9}) here.
845
60.3k
        _condition_cache_digest = *options.condition_cache_digest;
846
60.3k
    } else {
847
        // An explicit scanner digest is split-scoped. Restore the init-time digest when a later
848
        // standalone split omits it instead of leaking the previous split's RF payload into its key.
849
137
        _condition_cache_digest = _initial_condition_cache_digest;
850
137
    }
851
60.4k
    if (options.conjuncts.has_value()) {
852
60.3k
        _conjuncts = *options.conjuncts;
853
60.3k
    }
854
    // Update to current split format to handle ORC/PARQUET files in one table.
855
60.4k
    _format = options.current_split_format;
856
60.4k
    _partition_values = std::move(options.partition_values);
857
60.4k
    _current_task.reset();
858
60.4k
    _current_file_description.reset();
859
60.4k
    _current_file_range_desc = options.current_range;
860
60.4k
    _current_range_compress_type = options.current_range.__isset.compress_type
861
60.4k
                                           ? options.current_range.compress_type
862
60.4k
                                           : TFileCompressType::UNKNOWN;
863
60.4k
    _current_range_load_id = options.current_range.__isset.load_id
864
60.4k
                                     ? std::make_optional(options.current_range.load_id)
865
60.4k
                                     : std::nullopt;
866
60.4k
    _global_rowid_context = options.global_rowid_context;
867
60.4k
    _delete_rows = nullptr;
868
60.4k
    _deletion_vector = nullptr;
869
60.4k
    _aggregate_pushdown_tried = false;
870
60.4k
    _remaining_table_level_count = -1;
871
60.4k
    _current_reader_reached_eof = false;
872
60.4k
    RETURN_IF_ERROR(_evaluate_partition_prune_conjuncts(options.partition_prune_conjuncts,
873
60.4k
                                                        &_current_split_pruned));
874
60.4k
    if (_current_split_pruned) {
875
287
        COUNTER_UPDATE(_profile.runtime_filter_partition_pruned_range_counter, 1);
876
287
        return Status::OK();
877
287
    }
878
60.2k
    _current_task = std::make_unique<ScanTask>();
879
60.2k
    _current_task->data_file = create_file_description(options.current_range);
880
60.2k
    _current_file_description = *_current_task->data_file;
881
    // A table-level row count is only equivalent to scanning the split when no row predicate is
882
    // active and no predicate can arrive later. The metadata path can return several batches for
883
    // one split; after its first synthetic batch there is no way to recover the real rows if a
884
    // runtime filter arrives before the next scheduler turn.
885
60.2k
    if (_push_down_agg_type == TPushAggOp::type::COUNT && options.all_runtime_filters_applied &&
886
60.2k
        _conjuncts.empty() && options.current_range.__isset.table_format_params &&
887
60.2k
        options.current_range.table_format_params.__isset.table_level_row_count) {
888
2.11k
        DORIS_CHECK(options.current_range.table_format_params.table_level_row_count >= -1);
889
2.11k
        _remaining_table_level_count =
890
2.11k
                options.current_range.table_format_params.table_level_row_count;
891
2.11k
    }
892
60.2k
    if (_is_table_level_count_active()) {
893
148
        return Status::OK();
894
148
    }
895
60.0k
    return _parse_delete_predicates(options);
896
60.2k
}
897
898
Status TableReader::_evaluate_partition_prune_conjuncts(const VExprContextSPtrs& conjuncts,
899
60.4k
                                                        bool* can_filter_all) {
900
60.4k
    DORIS_CHECK(can_filter_all != nullptr);
901
60.4k
    SCOPED_TIMER(_profile.runtime_filter_partition_prune_timer);
902
60.4k
    *can_filter_all = false;
903
60.4k
    if (conjuncts.empty() || _partition_values.empty()) {
904
57.3k
        return Status::OK();
905
57.3k
    }
906
907
3.10k
    VExprContextSPtrs partition_conjuncts;
908
4.32k
    for (const auto& conjunct : conjuncts) {
909
4.32k
        DORIS_CHECK(conjunct != nullptr);
910
4.32k
        DORIS_CHECK(conjunct->root() != nullptr);
911
        // Keep only the safe prefix of the original conjunct order. If an unsafe conjunct is
912
        // skipped, a later predicate could prune the split before the unsafe one reaches its
913
        // normal row-level evaluation point.
914
4.32k
        if (!_is_safe_to_pre_execute(conjunct)) {
915
1
            break;
916
1
        }
917
4.32k
        std::set<GlobalIndex> global_indices;
918
4.32k
        collect_global_indices(conjunct->root(), &global_indices);
919
4.32k
        if (global_indices.empty()) {
920
0
            continue;
921
0
        }
922
4.38k
        const bool partition_only = std::ranges::all_of(global_indices, [&](GlobalIndex index) {
923
4.38k
            if (index.value() >= _projected_columns.size()) {
924
0
                return false;
925
0
            }
926
4.38k
            const auto& column = _projected_columns[index.value()];
927
4.38k
            return column.is_partition_key &&
928
4.38k
                   find_partition_value(column, _partition_values) != nullptr;
929
4.38k
        });
930
4.32k
        if (partition_only) {
931
2.76k
            partition_conjuncts.push_back(conjunct);
932
2.76k
        }
933
4.32k
    }
934
3.10k
    if (partition_conjuncts.empty()) {
935
1.14k
        return Status::OK();
936
1.14k
    }
937
938
1.96k
    Block block;
939
1.96k
    RETURN_IF_ERROR(_build_partition_prune_block(&block));
940
1.96k
    RowDescriptor row_desc;
941
2.76k
    for (const auto& conjunct : partition_conjuncts) {
942
2.76k
        RETURN_IF_ERROR(conjunct->prepare(_runtime_state, row_desc));
943
2.76k
        RETURN_IF_ERROR(conjunct->open(_runtime_state));
944
2.76k
    }
945
1.96k
    IColumn::Filter result_filter(block.rows(), 1);
946
1.96k
    return VExprContext::execute_conjuncts(partition_conjuncts, nullptr, &block, &result_filter,
947
1.96k
                                           can_filter_all);
948
1.96k
}
949
950
83.8k
bool TableReader::_is_safe_to_pre_execute(const VExprContextSPtr& conjunct) {
951
83.8k
    DORIS_CHECK(conjunct != nullptr);
952
83.8k
    DORIS_CHECK(conjunct->root() != nullptr);
953
83.8k
    const auto root = conjunct->root();
954
83.8k
    const auto impl = root->get_impl();
955
83.8k
    const auto predicate = impl != nullptr ? impl : root;
956
    // Split pruning evaluates a predicate once before any file rows are read. Reordering
957
    // non-deterministic or error-preserving expressions can change their row-level semantics,
958
    // even when every referenced slot is a partition column or maps to a constant entry.
959
83.8k
    return predicate->is_safe_to_execute_on_selected_rows();
960
83.8k
}
961
962
1.97k
Status TableReader::_build_partition_prune_block(Block* block) const {
963
1.97k
    DORIS_CHECK(block != nullptr);
964
1.97k
    DORIS_CHECK(!_projected_columns.empty());
965
1.97k
    block->clear();
966
5.74k
    for (const auto& column : _projected_columns) {
967
5.74k
        DORIS_CHECK(column.type != nullptr);
968
5.74k
        ColumnPtr value_column = column.type->create_column_const_with_default_value(1);
969
5.74k
        if (column.is_partition_key) {
970
2.80k
            const auto* partition_value = find_partition_value(column, _partition_values);
971
2.80k
            if (partition_value != nullptr) {
972
2.80k
                value_column = column.type->create_column_const(1, *partition_value);
973
2.80k
            }
974
2.80k
        }
975
5.74k
        block->insert({std::move(value_column), column.type, column.name});
976
5.74k
    }
977
1.97k
    return Status::OK();
978
1.97k
}
979
980
59.9k
Status TableReader::_parse_delete_predicates(const SplitReadOptions& options) {
981
59.9k
    DeleteFileDesc desc {.fs_name = options.current_range.fs_name};
982
59.9k
    bool has_delete_file = false;
983
59.9k
    RETURN_IF_ERROR(_parse_deletion_vector_file(options.current_range.table_format_params, &desc,
984
59.9k
                                                &has_delete_file));
985
59.9k
    if (has_delete_file) {
986
3.63k
        DORIS_CHECK(options.cache != nullptr);
987
3.63k
        Status create_status = Status::OK();
988
989
3.63k
        bool decoded_cache_hit = false;
990
3.63k
        _deletion_vector = options.cache->get<DeletionVector>(
991
3.63k
                desc.key,
992
3.63k
                [&]() -> DeletionVector* {
993
1.44k
                    auto deletion_vector = std::make_unique<DeletionVector>();
994
995
1.44k
                    DeletionVectorReader dv_reader(_runtime_state, _scanner_profile, *_scan_params,
996
1.44k
                                                   desc, _io_ctx.get());
997
1.44k
                    create_status = dv_reader.open();
998
1.44k
                    if (!create_status.ok()) [[unlikely]] {
999
0
                        return nullptr;
1000
0
                    }
1001
1002
1.44k
                    size_t bytes_read = desc.size;
1003
1.44k
                    std::vector<char> buffer(bytes_read);
1004
1.44k
                    DBUG_EXECUTE_IF("TableReader.parse_deletion_vector.io_error", {
1005
1.44k
                        create_status =
1006
1.44k
                                Status::IOError("injected format v2 deletion vector read failure");
1007
1.44k
                        return nullptr;
1008
1.44k
                    });
1009
1.43k
                    DBUG_EXECUTE_IF("TableReader.parse_deletion_vector.should_stop", {
1010
1.43k
                        create_status = Status::EndOfFile("stop read.");
1011
1.43k
                        return nullptr;
1012
1.43k
                    });
1013
1.43k
                    create_status =
1014
1.43k
                            dv_reader.read_at(desc.start_offset, {buffer.data(), bytes_read});
1015
1.43k
                    const auto& file_cache_stats = dv_reader.file_cache_statistics();
1016
1.43k
                    COUNTER_UPDATE(_profile.dv_file_cache_hit_count,
1017
1.43k
                                   file_cache_stats.num_local_io_total);
1018
1.43k
                    COUNTER_UPDATE(_profile.dv_file_cache_miss_count,
1019
1.43k
                                   file_cache_stats.num_remote_io_total);
1020
1.43k
                    COUNTER_UPDATE(_profile.dv_file_cache_peer_read_count,
1021
1.43k
                                   file_cache_stats.num_peer_io_total);
1022
1.43k
                    if (!create_status.ok()) [[unlikely]] {
1023
0
                        return nullptr;
1024
0
                    }
1025
1026
1.43k
                    const char* buf = buffer.data();
1027
1.43k
                    SCOPED_TIMER(_profile.parse_delete_file_time);
1028
1.43k
                    create_status = parse_deletion_vector(buf, bytes_read, desc.format,
1029
1.43k
                                                          deletion_vector.get());
1030
1.43k
                    if (!create_status.ok()) [[unlikely]] {
1031
1
                        return nullptr;
1032
1
                    }
1033
1.43k
                    COUNTER_UPDATE(_profile.num_delete_rows, deletion_vector->cardinality());
1034
1.43k
                    return deletion_vector.release();
1035
1.43k
                },
1036
3.63k
                &decoded_cache_hit);
1037
3.63k
        RETURN_IF_ERROR(create_status);
1038
3.62k
        COUNTER_UPDATE(decoded_cache_hit ? _profile.decoded_dv_cache_hit_count
1039
3.62k
                                         : _profile.decoded_dv_cache_miss_count,
1040
3.62k
                       1);
1041
3.62k
    }
1042
1043
59.9k
    return Status::OK();
1044
59.9k
}
1045
} // namespace doris::format