Coverage Report

Created: 2026-07-21 09:58

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