Coverage Report

Created: 2026-07-10 05:35

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_map.h"
37
#include "core/data_type/data_type_struct.h"
38
#include "exprs/vexpr_context.h"
39
#include "exprs/vslot_ref.h"
40
#include "format/table/deletion_vector_reader.h"
41
#include "format/table/iceberg_delete_file_reader_helper.h"
42
#include "format/table/paimon_reader.h"
43
#include "format_v2/column_mapper.h"
44
#include "format_v2/delimited_text/csv_reader.h"
45
#include "format_v2/delimited_text/text_reader.h"
46
#include "format_v2/json/json_reader.h"
47
#include "format_v2/native/native_reader.h"
48
#include "format_v2/orc/orc_reader.h"
49
#include "format_v2/parquet/parquet_reader.h"
50
#include "storage/segment/condition_cache.h"
51
#include "util/debug_points.h"
52
#include "util/string_util.h"
53
54
namespace doris::format {
55
namespace {
56
57
template <typename T, typename Formatter>
58
61
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
59
61
    std::ostringstream out;
60
61
    out << "[";
61
70
    for (size_t i = 0; i < values.size(); ++i) {
62
9
        if (i > 0) {
63
3
            out << ", ";
64
3
        }
65
9
        out << formatter(values[i]);
66
9
    }
67
61
    out << "]";
68
61
    return out.str();
69
61
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_16ColumnDefinitionEZNKS0_11TableReader12debug_stringB5cxx11EvE3$_0EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
58
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
59
12
    std::ostringstream out;
60
12
    out << "[";
61
14
    for (size_t i = 0; i < values.size(); ++i) {
62
2
        if (i > 0) {
63
1
            out << ", ";
64
1
        }
65
2
        out << formatter(values[i]);
66
2
    }
67
12
    out << "]";
68
12
    return out.str();
69
12
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_11TableFilterEZNKS0_11TableReader12debug_stringB5cxx11EvE3$_1EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
58
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
59
12
    std::ostringstream out;
60
12
    out << "[";
61
13
    for (size_t i = 0; i < values.size(); ++i) {
62
1
        if (i > 0) {
63
0
            out << ", ";
64
0
        }
65
1
        out << formatter(values[i]);
66
1
    }
67
12
    out << "]";
68
12
    return out.str();
69
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
58
1
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
59
1
    std::ostringstream out;
60
1
    out << "[";
61
2
    for (size_t i = 0; i < values.size(); ++i) {
62
1
        if (i > 0) {
63
0
            out << ", ";
64
0
        }
65
1
        out << formatter(values[i]);
66
1
    }
67
1
    out << "]";
68
1
    return out.str();
69
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
58
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
59
12
    std::ostringstream out;
60
12
    out << "[";
61
13
    for (size_t i = 0; i < values.size(); ++i) {
62
1
        if (i > 0) {
63
0
            out << ", ";
64
0
        }
65
1
        out << formatter(values[i]);
66
1
    }
67
12
    out << "]";
68
12
    return out.str();
69
12
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_16ColumnDefinitionEZNKS0_11TableReader12debug_stringB5cxx11EvE3$_3EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
58
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
59
12
    std::ostringstream out;
60
12
    out << "[";
61
14
    for (size_t i = 0; i < values.size(); ++i) {
62
2
        if (i > 0) {
63
1
            out << ", ";
64
1
        }
65
2
        out << formatter(values[i]);
66
2
    }
67
12
    out << "]";
68
12
    return out.str();
69
12
}
table_reader.cpp:_ZN5doris6format12_GLOBAL__N_131join_table_reader_debug_stringsINS0_11TableReader15FileBlockColumnEZNKS3_12debug_stringB5cxx11EvE3$_4EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
58
12
std::string join_table_reader_debug_strings(const std::vector<T>& values, Formatter formatter) {
59
12
    std::ostringstream out;
60
12
    out << "[";
61
14
    for (size_t i = 0; i < values.size(); ++i) {
62
2
        if (i > 0) {
63
1
            out << ", ";
64
1
        }
65
2
        out << formatter(values[i]);
66
2
    }
67
12
    out << "]";
68
12
    return out.str();
69
12
}
70
71
12
std::string file_format_to_string(FileFormat format) {
72
12
    switch (format) {
73
5
    case FileFormat::PARQUET:
74
5
        return "PARQUET";
75
1
    case FileFormat::ORC:
76
1
        return "ORC";
77
1
    case FileFormat::CSV:
78
1
        return "CSV";
79
1
    case FileFormat::JSON:
80
1
        return "JSON";
81
1
    case FileFormat::TEXT:
82
1
        return "TEXT";
83
1
    case FileFormat::JNI:
84
1
        return "JNI";
85
1
    case FileFormat::NATIVE:
86
1
        return "NATIVE";
87
1
    case FileFormat::ARROW:
88
1
        return "ARROW";
89
12
    }
90
0
    return "UNKNOWN";
91
12
}
92
93
12
std::string push_down_agg_to_string(TPushAggOp::type op) {
94
12
    switch (op) {
95
8
    case TPushAggOp::NONE:
96
8
        return "NONE";
97
1
    case TPushAggOp::COUNT:
98
1
        return "COUNT";
99
1
    case TPushAggOp::MINMAX:
100
1
        return "MINMAX";
101
1
    case TPushAggOp::MIX:
102
1
        return "MIX";
103
1
    case TPushAggOp::COUNT_ON_INDEX:
104
1
        return "COUNT_ON_INDEX";
105
12
    }
106
0
    return "UNKNOWN";
107
12
}
108
109
12
std::string current_file_debug_string(const std::unique_ptr<ScanTask>& task) {
110
12
    if (task == nullptr || task->data_file == nullptr) {
111
11
        return "null";
112
11
    }
113
1
    const auto& file = *task->data_file;
114
1
    std::ostringstream out;
115
1
    out << "FileDescription{path=" << file.path << ", file_size=" << file.file_size
116
1
        << ", range_start_offset=" << file.range_start_offset << ", range_size=" << file.range_size
117
1
        << ", mtime=" << file.mtime << ", fs_name=" << file.fs_name
118
1
        << ", file_cache_admission=" << file.file_cache_admission << "}";
119
1
    return out.str();
120
12
}
121
122
12
std::string partition_values_debug_string(const std::map<std::string, Field>& partition_values) {
123
12
    std::ostringstream out;
124
12
    out << "{";
125
12
    size_t idx = 0;
126
12
    for (const auto& [key, _] : partition_values) {
127
1
        if (idx++ > 0) {
128
0
            out << ", ";
129
0
        }
130
1
        out << key;
131
1
    }
132
12
    out << "}";
133
12
    return out.str();
134
12
}
135
136
2.18M
const schema::external::TField* get_field_ptr(const schema::external::TFieldPtr& field_ptr) {
137
2.18M
    if (!field_ptr.__isset.field_ptr || field_ptr.field_ptr == nullptr) {
138
0
        return nullptr;
139
0
    }
140
2.18M
    return field_ptr.field_ptr.get();
141
2.18M
}
142
143
2.16M
bool external_field_matches_name(const schema::external::TField& field, const std::string& name) {
144
2.16M
    if (field.__isset.name && to_lower(field.name) == to_lower(name)) {
145
119k
        return true;
146
119k
    }
147
2.04M
    return field.__isset.name_mapping &&
148
2.04M
           std::ranges::any_of(field.name_mapping, [&](const std::string& alias) {
149
16
               return to_lower(alias) == to_lower(name);
150
16
           });
151
2.16M
}
152
153
DataTypePtr find_struct_child_type_by_external_field(const DataTypeStruct& struct_type,
154
27.9k
                                                     const schema::external::TField& field) {
155
58.3k
    for (size_t field_idx = 0; field_idx < struct_type.get_elements().size(); ++field_idx) {
156
58.3k
        if (external_field_matches_name(field, struct_type.get_element_name(field_idx))) {
157
28.0k
            return struct_type.get_element(field_idx);
158
28.0k
        }
159
58.3k
    }
160
18.4E
    return nullptr;
161
27.9k
}
162
163
ColumnDefinition build_schema_column_from_external_field(const schema::external::TField& field,
164
167k
                                                         DataTypePtr type) {
165
167k
    ColumnDefinition column {
166
18.4E
            .identifier = field.__isset.id ? Field::create_field<TYPE_INT>(field.id) : Field {},
167
167k
            .name = field.__isset.name ? field.name : "",
168
167k
            .name_mapping =
169
167k
                    field.__isset.name_mapping ? field.name_mapping : std::vector<std::string> {},
170
167k
            .type = std::move(type),
171
167k
            .children = {},
172
167k
            .default_expr = nullptr,
173
167k
            .is_partition_key = false,
174
167k
    };
175
167k
    if (column.type == nullptr || !field.__isset.nestedField) {
176
125k
        return column;
177
125k
    }
178
179
42.7k
    const auto nested_type = remove_nullable(column.type);
180
42.7k
    switch (nested_type->get_primitive_type()) {
181
12.2k
    case TYPE_STRUCT: {
182
12.2k
        if (!field.nestedField.__isset.struct_field ||
183
12.2k
            !field.nestedField.struct_field.__isset.fields) {
184
0
            return column;
185
0
        }
186
12.2k
        const auto& struct_type = assert_cast<const DataTypeStruct&>(*nested_type);
187
28.0k
        for (const auto& child_ptr : field.nestedField.struct_field.fields) {
188
28.0k
            const auto* child_field = get_field_ptr(child_ptr);
189
28.0k
            if (child_field == nullptr || !child_field->__isset.name) {
190
0
                continue;
191
0
            }
192
28.0k
            auto child_type = find_struct_child_type_by_external_field(struct_type, *child_field);
193
28.0k
            if (child_type == nullptr) {
194
0
                continue;
195
0
            }
196
28.0k
            column.children.push_back(
197
28.0k
                    build_schema_column_from_external_field(*child_field, child_type));
198
28.0k
        }
199
12.2k
        break;
200
12.2k
    }
201
12.8k
    case TYPE_ARRAY: {
202
12.8k
        if (!field.nestedField.__isset.array_field ||
203
12.8k
            !field.nestedField.array_field.__isset.item_field) {
204
0
            return column;
205
0
        }
206
12.8k
        const auto* item_field = get_field_ptr(field.nestedField.array_field.item_field);
207
12.8k
        if (item_field == nullptr) {
208
0
            return column;
209
0
        }
210
12.8k
        const auto& array_type = assert_cast<const DataTypeArray&>(*nested_type);
211
12.8k
        auto child =
212
12.8k
                build_schema_column_from_external_field(*item_field, array_type.get_nested_type());
213
12.8k
        child.name = "element";
214
12.8k
        if (child.has_identifier_name()) {
215
0
            child.identifier = Field::create_field<TYPE_STRING>(child.name);
216
0
        }
217
12.8k
        column.children.push_back(std::move(child));
218
12.8k
        break;
219
12.8k
    }
220
17.6k
    case TYPE_MAP: {
221
17.6k
        if (!field.nestedField.__isset.map_field ||
222
17.6k
            !field.nestedField.map_field.__isset.key_field ||
223
17.6k
            !field.nestedField.map_field.__isset.value_field) {
224
0
            return column;
225
0
        }
226
17.6k
        const auto& map_type = assert_cast<const DataTypeMap&>(*nested_type);
227
17.6k
        const auto* key_field = get_field_ptr(field.nestedField.map_field.key_field);
228
17.6k
        if (key_field != nullptr) {
229
17.6k
            auto child =
230
17.6k
                    build_schema_column_from_external_field(*key_field, map_type.get_key_type());
231
17.6k
            child.name = "key";
232
17.6k
            if (child.has_identifier_name()) {
233
0
                child.identifier = Field::create_field<TYPE_STRING>(child.name);
234
0
            }
235
17.6k
            column.children.push_back(std::move(child));
236
17.6k
        }
237
17.6k
        const auto* value_field = get_field_ptr(field.nestedField.map_field.value_field);
238
17.6k
        if (value_field != nullptr) {
239
17.6k
            auto child = build_schema_column_from_external_field(*value_field,
240
17.6k
                                                                 map_type.get_value_type());
241
17.6k
            child.name = "value";
242
17.6k
            if (child.has_identifier_name()) {
243
0
                child.identifier = Field::create_field<TYPE_STRING>(child.name);
244
0
            }
245
17.6k
            column.children.push_back(std::move(child));
246
17.6k
        }
247
17.6k
        break;
248
17.6k
    }
249
0
    default:
250
0
        break;
251
42.7k
    }
252
42.7k
    return column;
253
42.7k
}
254
255
const schema::external::TField* find_external_root_field(const TFileScanRangeParams* params,
256
280k
                                                         const ColumnDefinition& column) {
257
280k
    if (params == nullptr || !params->__isset.history_schema_info ||
258
280k
        params->history_schema_info.empty()) {
259
188k
        return nullptr;
260
188k
    }
261
92.2k
    const auto* schema = &params->history_schema_info.front();
262
92.2k
    if (params->__isset.current_schema_id) {
263
92.2k
        for (const auto& candidate_schema : params->history_schema_info) {
264
92.2k
            if (candidate_schema.__isset.schema_id &&
265
92.2k
                candidate_schema.schema_id == params->current_schema_id) {
266
92.2k
                schema = &candidate_schema;
267
92.2k
                break;
268
92.2k
            }
269
92.2k
        }
270
92.2k
    }
271
92.2k
    if (!schema->__isset.root_field || !schema->root_field.__isset.fields) {
272
0
        return nullptr;
273
0
    }
274
2.10M
    for (const auto& field_ptr : schema->root_field.fields) {
275
2.10M
        const auto* field = get_field_ptr(field_ptr);
276
2.10M
        if (field == nullptr) {
277
0
            continue;
278
0
        }
279
2.10M
        if (external_field_matches_name(*field, column.name)) {
280
91.8k
            return field;
281
91.8k
        }
282
2.10M
    }
283
368
    return nullptr;
284
92.2k
}
285
286
2
std::string expr_context_debug_string(const VExprContextSPtr& context) {
287
2
    if (context == nullptr) {
288
0
        return "null";
289
0
    }
290
2
    const auto root = context->root();
291
2
    if (root == nullptr) {
292
0
        return "VExprContext{root=null}";
293
0
    }
294
2
    std::ostringstream out;
295
2
    out << "VExprContext{root_name=" << root->expr_name() << ", root_debug=" << root->debug_string()
296
2
        << "}";
297
2
    return out.str();
298
2
}
299
300
1
std::string table_filter_debug_string(const TableFilter& filter) {
301
1
    std::ostringstream out;
302
1
    out << "TableFilter{conjunct=" << expr_context_debug_string(filter.conjunct)
303
1
        << ", global_indices="
304
1
        << join_table_reader_debug_strings(
305
1
                   filter.global_indices,
306
1
                   [](GlobalIndex global_index) { return std::to_string(global_index.value()); })
307
1
        << "}";
308
1
    return out.str();
309
1
}
310
311
25.2k
bool contains_runtime_filter(const VExprContextSPtrs& conjuncts) {
312
26.1k
    return std::ranges::any_of(conjuncts, [](const auto& conjunct) {
313
26.1k
        return conjunct != nullptr && conjunct->root() != nullptr &&
314
26.1k
               conjunct->root()->is_rf_wrapper();
315
26.1k
    });
316
25.2k
}
317
318
259k
void collect_global_indices(const VExprSPtr& expr, std::set<GlobalIndex>* global_indices) {
319
259k
    if (expr == nullptr) {
320
0
        return;
321
0
    }
322
259k
    if (expr->is_rf_wrapper()) {
323
        // RuntimeFilterExpr wraps a real predicate expression but its own thrift node can still
324
        // look like SLOT_REF. Collect indices from the wrapped predicate; do not cast the wrapper
325
        // itself to VSlotRef.
326
7.75k
        collect_global_indices(expr->get_impl(), global_indices);
327
7.75k
        return;
328
7.75k
    }
329
252k
    if (expr->is_slot_ref()) {
330
82.7k
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
331
82.7k
        DORIS_CHECK(slot_ref->column_id() >= 0);
332
82.7k
        global_indices->insert(GlobalIndex(cast_set<size_t>(slot_ref->column_id())));
333
82.7k
    }
334
252k
    for (const auto& child : expr->children()) {
335
170k
        collect_global_indices(child, global_indices);
336
170k
    }
337
252k
}
338
339
Status build_table_filters_from_conjunct(const VExprContextSPtr& conjunct, RuntimeState* state,
340
81.6k
                                         std::vector<TableFilter>* table_filters) {
341
81.6k
    if (conjunct == nullptr) {
342
0
        return Status::OK();
343
0
    }
344
81.6k
    std::set<GlobalIndex> global_indices;
345
81.6k
    collect_global_indices(conjunct->root(), &global_indices);
346
81.7k
    if (!global_indices.empty()) {
347
81.7k
        TableFilter table_filter;
348
81.7k
        VExprSPtr filter_root;
349
81.7k
        RETURN_IF_ERROR(clone_table_expr_tree(conjunct->root(), &filter_root));
350
81.7k
        table_filter.conjunct = VExprContext::create_shared(std::move(filter_root));
351
82.8k
        for (const auto global_index : global_indices) {
352
82.8k
            table_filter.global_indices.push_back(global_index);
353
82.8k
        }
354
81.7k
        table_filters->push_back(std::move(table_filter));
355
81.7k
    }
356
81.6k
    return Status::OK();
357
81.6k
}
358
359
Status parse_deletion_vector(const char* buf, size_t buffer_size, DeleteFileDesc::Format format,
360
1.66k
                             DeleteRows* delete_rows) {
361
1.66k
    DORIS_CHECK(buf != nullptr);
362
1.66k
    DORIS_CHECK(delete_rows != nullptr);
363
1.66k
    DORIS_CHECK(format == DeleteFileDesc::Format::PAIMON ||
364
1.66k
                format == DeleteFileDesc::Format::ICEBERG);
365
366
1.66k
    if (format == DeleteFileDesc::Format::PAIMON) {
367
229
        RETURN_IF_ERROR(decode_paimon_deletion_vector_buffer(buf, buffer_size, delete_rows));
368
229
        return Status::OK();
369
229
    }
370
371
1.43k
    roaring::Roaring64Map bitmap;
372
1.43k
    RETURN_IF_ERROR(decode_iceberg_deletion_vector_buffer(buf, buffer_size, &bitmap));
373
1.43k
    delete_rows->reserve(bitmap.cardinality());
374
7.14M
    for (auto it = bitmap.begin(); it != bitmap.end(); it++) {
375
7.14M
        delete_rows->push_back(cast_set<int64_t>(*it));
376
7.14M
    }
377
1.43k
    return Status::OK();
378
1.43k
}
379
380
} // namespace
381
382
std::shared_ptr<io::FileSystemProperties> create_system_properties(
383
54.6k
        const TFileScanRangeParams* scan_params) {
384
54.6k
    auto system_properties = std::make_shared<io::FileSystemProperties>();
385
54.6k
    if (scan_params == nullptr || !scan_params->__isset.file_type) {
386
6.76k
        system_properties->system_type = TFileType::FILE_LOCAL;
387
6.76k
        return system_properties;
388
6.76k
    }
389
47.9k
    system_properties->system_type = scan_params->file_type;
390
47.9k
    system_properties->properties = scan_params->properties;
391
47.9k
    system_properties->hdfs_params = scan_params->hdfs_params;
392
47.9k
    if (scan_params->__isset.broker_addresses) {
393
0
        system_properties->broker_addresses.assign(scan_params->broker_addresses.begin(),
394
0
                                                   scan_params->broker_addresses.end());
395
0
    }
396
47.9k
    return system_properties;
397
54.6k
}
398
399
12
std::string TableReader::debug_string() const {
400
12
    std::ostringstream out;
401
12
    out << "TableReader{format=" << file_format_to_string(_format)
402
12
        << ", push_down_agg_type=" << push_down_agg_to_string(_push_down_agg_type)
403
12
        << ", aggregate_pushdown_tried=" << _aggregate_pushdown_tried
404
12
        << ", has_current_reader=" << (_data_reader.reader != nullptr)
405
12
        << ", has_current_task=" << (_current_task != nullptr)
406
12
        << ", current_file=" << current_file_debug_string(_current_task)
407
12
        << ", has_delete_rows=" << (_delete_rows != nullptr)
408
12
        << ", delete_row_count=" << (_delete_rows == nullptr ? 0 : _delete_rows->size())
409
12
        << ", has_system_properties=" << (_system_properties != nullptr) << ", system_type="
410
12
        << (_system_properties == nullptr ? static_cast<int>(TFileType::FILE_LOCAL)
411
12
                                          : static_cast<int>(_system_properties->system_type))
412
12
        << ", has_scan_params=" << (_scan_params != nullptr)
413
12
        << ", has_io_ctx=" << (_io_ctx != nullptr)
414
12
        << ", has_runtime_state=" << (_runtime_state != nullptr)
415
12
        << ", has_scanner_profile=" << (_scanner_profile != nullptr)
416
12
        << ", mapper_options=" << _mapper_options.debug_string() << ", projected_columns="
417
12
        << join_table_reader_debug_strings(
418
12
                   _projected_columns,
419
12
                   [](const ColumnDefinition& column) { return column.debug_string(); })
420
12
        << ", partition_values=" << partition_values_debug_string(_partition_values)
421
12
        << ", table_filters="
422
12
        << join_table_reader_debug_strings(
423
12
                   _table_filters,
424
12
                   [](const TableFilter& filter) { return table_filter_debug_string(filter); })
425
12
        << ", conjunct_count=" << _conjuncts.size() << ", conjuncts="
426
12
        << join_table_reader_debug_strings(_conjuncts,
427
12
                                           [](const VExprContextSPtr& conjunct) {
428
1
                                               return expr_context_debug_string(conjunct);
429
1
                                           })
430
12
        << ", file_schema="
431
12
        << join_table_reader_debug_strings(
432
12
                   _data_reader.file_schema,
433
12
                   [](const ColumnDefinition& field) { return field.debug_string(); })
434
12
        << ", file_block_layout="
435
12
        << join_table_reader_debug_strings(
436
12
                   _data_reader.file_block_layout,
437
12
                   [](const FileBlockColumn& column) {
438
2
                       std::ostringstream column_out;
439
2
                       column_out << "FileBlockColumn{file_column_id=" << column.file_column_id
440
2
                                  << ", name=" << column.name << ", type="
441
2
                                  << (column.type == nullptr ? "null" : column.type->get_name())
442
2
                                  << "}";
443
2
                       return column_out.str();
444
2
                   })
445
12
        << ", block_template_columns=" << _data_reader.block_template.columns()
446
12
        << ", column_mapper="
447
12
        << (_data_reader.column_mapper == nullptr ? "null"
448
12
                                                  : _data_reader.column_mapper->debug_string())
449
12
        << "}";
450
12
    return out.str();
451
12
}
452
453
Status TableReader::annotate_projected_column(const TFileScanSlotInfo& slot_info,
454
                                              ProjectedColumnBuildContext* context,
455
280k
                                              ColumnDefinition* column) const {
456
280k
    (void)slot_info;
457
280k
    DORIS_CHECK(context != nullptr);
458
280k
    DORIS_CHECK(column != nullptr);
459
280k
    context->schema_column.reset();
460
280k
    const auto* schema_field = find_external_root_field(context->scan_params, *column);
461
280k
    if (schema_field == nullptr) {
462
189k
        return Status::OK();
463
189k
    }
464
91.8k
    context->schema_column = build_schema_column_from_external_field(*schema_field, column->type);
465
91.8k
    column->identifier = context->schema_column->identifier;
466
91.8k
    column->name_mapping = context->schema_column->name_mapping;
467
91.8k
    return Status::OK();
468
280k
}
469
470
54.6k
Status TableReader::init(TableReadOptions&& options) {
471
54.6k
    _scan_params = options.scan_params;
472
54.6k
    _format = options.format;
473
54.6k
    _io_ctx = options.io_ctx;
474
54.6k
    _runtime_state = options.runtime_state;
475
54.6k
    _scanner_profile = options.scanner_profile;
476
54.6k
    _file_slot_descs = options.file_slot_descs;
477
54.6k
    _push_down_agg_type = options.push_down_agg_type;
478
54.6k
    _condition_cache_digest = options.condition_cache_digest;
479
54.6k
    _projected_columns = std::move(options.projected_columns);
480
54.6k
    _system_properties = create_system_properties(_scan_params);
481
54.6k
    _mapper_options.mode = TableColumnMappingMode::BY_NAME;
482
54.6k
    _conjuncts = std::move(options.conjuncts);
483
484
54.6k
    if (_scanner_profile != nullptr) {
485
54.6k
        static const char* table_profile = "TableReader";
486
54.6k
        ADD_TIMER_WITH_LEVEL(_scanner_profile, table_profile, 1);
487
54.6k
        _profile.num_delete_files = ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "NumDeleteFiles",
488
54.6k
                                                                 TUnit::UNIT, table_profile, 1);
489
54.6k
        _profile.num_delete_rows = ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "NumDeleteRows",
490
54.6k
                                                                TUnit::UNIT, table_profile, 1);
491
54.6k
        _profile.parse_delete_file_time = ADD_CHILD_TIMER_WITH_LEVEL(
492
54.6k
                _scanner_profile, "ParseDeleteFileTime", table_profile, 1);
493
54.6k
        _profile.exec_timer =
494
54.6k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "GetBlockTime", table_profile, 1);
495
54.6k
        _profile.prepare_split_timer =
496
54.6k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "PrepareSplitTime", table_profile, 1);
497
54.6k
        _profile.finalize_timer =
498
54.6k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "FinalizeBlockTime", table_profile, 1);
499
54.6k
        _profile.create_reader_timer =
500
54.6k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "CreateReaderTime", table_profile, 1);
501
54.6k
        _profile.pushdown_agg_timer =
502
54.6k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "PushDownAggTime", table_profile, 1);
503
54.6k
        _profile.open_reader_timer =
504
54.6k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "OpenReaderTime", table_profile, 1);
505
54.6k
    }
506
54.6k
    return Status::OK();
507
54.6k
}
508
509
118k
Status TableReader::_build_table_filters_from_conjuncts() {
510
118k
    _table_filters.clear();
511
118k
    for (const auto& conjunct : _conjuncts) {
512
81.6k
        RETURN_IF_ERROR(
513
81.6k
                build_table_filters_from_conjunct(conjunct, _runtime_state, &_table_filters));
514
81.6k
    }
515
118k
    return Status::OK();
516
118k
}
517
518
116k
Status TableReader::_open_local_filter_exprs(const FileScanRequest& file_request) {
519
116k
    RowDescriptor row_desc;
520
116k
    for (const auto& conjunct : file_request.conjuncts) {
521
70.8k
        RETURN_IF_ERROR(conjunct->prepare(_runtime_state, row_desc));
522
70.8k
        RETURN_IF_ERROR(conjunct->open(_runtime_state));
523
70.8k
    }
524
116k
    for (const auto& delete_conjunct : file_request.delete_conjuncts) {
525
29.6k
        RETURN_IF_ERROR(delete_conjunct->prepare(_runtime_state, row_desc));
526
29.6k
        RETURN_IF_ERROR(delete_conjunct->open(_runtime_state));
527
29.6k
    }
528
116k
    return Status::OK();
529
116k
}
530
531
116k
bool TableReader::_should_enable_condition_cache(const FileScanRequest& file_request) const {
532
116k
    if (_condition_cache_digest == 0 || _push_down_agg_type == TPushAggOp::type::COUNT ||
533
116k
        _current_file_description == std::nullopt || _data_reader.reader == nullptr) {
534
16.9k
        return false;
535
16.9k
    }
536
    // Condition cache is populated by file readers after evaluating file-local row-level
537
    // conjuncts. Metadata pruning can skip row groups/pages, but it does not produce a per-row
538
    // survivor bitmap that can safely populate the cache.
539
99.9k
    if (file_request.conjuncts.empty()) {
540
56.0k
        return false;
541
56.0k
    }
542
    // Delete files/deletion vectors are table-format state. They may change independently of the
543
    // data file path/mtime/size used by the external cache key, so caching their result can become
544
    // stale. Keep delete filtering enabled, but do not read or write condition cache.
545
43.8k
    if (_delete_rows != nullptr || !file_request.delete_conjuncts.empty()) {
546
18.5k
        return false;
547
18.5k
    }
548
    // Runtime filters can arrive late and their payload is not guaranteed to be represented by the
549
    // scan-local digest. Without a read-only mode, a MISS could insert a bitmap for P AND RF under
550
    // the digest for only P. This mirrors the old FileScanner guard.
551
25.2k
    return !contains_runtime_filter(file_request.conjuncts);
552
43.8k
}
553
554
116k
Status TableReader::_init_reader_condition_cache(const FileScanRequest& file_request) {
555
116k
    _condition_cache = nullptr;
556
116k
    _condition_cache_ctx = nullptr;
557
116k
    if (!_should_enable_condition_cache(file_request)) {
558
92.6k
        return Status::OK();
559
92.6k
    }
560
561
24.1k
    auto* cache = segment_v2::ConditionCache::instance();
562
24.1k
    if (cache == nullptr) {
563
0
        return Status::OK();
564
0
    }
565
24.1k
    const auto& file = *_current_file_description;
566
24.1k
    _condition_cache_key = segment_v2::ConditionCache::ExternalCacheKey(
567
24.1k
            file.path, file.mtime, file.file_size, _condition_cache_digest, file.range_start_offset,
568
24.1k
            file.range_size);
569
570
24.1k
    segment_v2::ConditionCacheHandle handle;
571
24.1k
    const bool condition_cache_hit = cache->lookup(_condition_cache_key, &handle);
572
24.1k
    if (condition_cache_hit) {
573
4.14k
        _condition_cache = handle.get_filter_result();
574
4.14k
        ++_condition_cache_hit_count;
575
20.0k
    } else {
576
20.0k
        const int64_t total_rows = _data_reader.reader->get_total_rows();
577
20.0k
        if (total_rows <= 0) {
578
15.5k
            return Status::OK();
579
15.5k
        }
580
        // Add one guard granule for split ranges that start in the middle of a granule. A guard
581
        // false bit beyond the real range never overlaps real rows, but avoids boundary overflow
582
        // when a reader marks the last partial granule.
583
4.45k
        const size_t num_granules = (total_rows + ConditionCacheContext::GRANULE_SIZE - 1) /
584
4.45k
                                    ConditionCacheContext::GRANULE_SIZE;
585
4.45k
        _condition_cache = std::make_shared<std::vector<bool>>(num_granules + 1, false);
586
4.45k
    }
587
588
8.59k
    if (_condition_cache != nullptr) {
589
8.55k
        _condition_cache_ctx = std::make_shared<ConditionCacheContext>();
590
8.55k
        _condition_cache_ctx->is_hit = condition_cache_hit;
591
8.55k
        _condition_cache_ctx->filter_result = _condition_cache;
592
8.55k
        _data_reader.reader->set_condition_cache_context(_condition_cache_ctx);
593
8.55k
    }
594
8.59k
    return Status::OK();
595
24.1k
}
596
597
118k
void TableReader::_finalize_reader_condition_cache() {
598
118k
    if (_condition_cache_ctx == nullptr || _condition_cache_ctx->is_hit) {
599
114k
        _condition_cache = nullptr;
600
114k
        _condition_cache_ctx = nullptr;
601
114k
        return;
602
114k
    }
603
    // LIMIT or scanner cancellation may close a reader before all selected row ranges are visited.
604
    // Unvisited granules remain false in a MISS bitmap, so inserting a partial bitmap would make a
605
    // later HIT skip valid rows. Only publish cache entries after the physical reader reaches EOF.
606
4.40k
    if (!_current_reader_reached_eof) {
607
69
        _condition_cache = nullptr;
608
69
        _condition_cache_ctx = nullptr;
609
69
        return;
610
69
    }
611
4.34k
    segment_v2::ConditionCache::instance()->insert(_condition_cache_key,
612
4.34k
                                                   std::move(_condition_cache));
613
4.34k
    _condition_cache = nullptr;
614
4.34k
    _condition_cache_ctx = nullptr;
615
4.34k
}
616
617
234k
Status TableReader::create_next_reader(bool* eos) {
618
234k
    SCOPED_TIMER(_profile.create_reader_timer);
619
234k
    DCHECK(_data_reader.reader == nullptr);
620
234k
    if (_current_task == nullptr) {
621
116k
        *eos = true;
622
116k
        return Status::OK();
623
116k
    }
624
625
118k
    RETURN_IF_ERROR(create_file_reader(&_data_reader.reader));
626
118k
    DORIS_CHECK(_data_reader.reader != nullptr);
627
118k
    if (_batch_size > 0) {
628
58.1k
        _data_reader.reader->set_batch_size(_batch_size);
629
58.1k
    }
630
118k
    Status st = _data_reader.reader->init(_runtime_state);
631
118k
    if (!st.ok()) {
632
14
        if (_io_ctx != nullptr && _io_ctx->should_stop && st.is<ErrorCode::END_OF_FILE>()) {
633
0
            *eos = true;
634
0
            _data_reader.reader.reset();
635
0
            return Status::OK();
636
0
        }
637
14
        return st;
638
14
    }
639
118k
    st = open_reader();
640
118k
    if (!st.ok()) {
641
0
        if (_io_ctx != nullptr && _io_ctx->should_stop && st.is<ErrorCode::END_OF_FILE>()) {
642
0
            *eos = true;
643
0
            _data_reader.reader.reset();
644
0
            return Status::OK();
645
0
        }
646
0
        return st;
647
0
    }
648
118k
    if (_data_reader.reader == nullptr) {
649
1.42k
        *eos = _current_task == nullptr;
650
1.42k
        return Status::OK();
651
1.42k
    }
652
116k
    *eos = false;
653
116k
    return Status::OK();
654
118k
}
655
656
118k
Status TableReader::create_file_reader(std::unique_ptr<FileReader>* reader) {
657
118k
    DORIS_CHECK(reader != nullptr);
658
118k
    const bool enable_mapping_timestamp_tz = _scan_params != nullptr &&
659
118k
                                             _scan_params->__isset.enable_mapping_timestamp_tz &&
660
118k
                                             _scan_params->enable_mapping_timestamp_tz;
661
118k
    if (_format == FileFormat::PARQUET) {
662
81.9k
        *reader = std::make_unique<format::parquet::ParquetReader>(
663
81.9k
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
664
81.9k
                _global_rowid_context, enable_mapping_timestamp_tz);
665
81.9k
        return Status::OK();
666
81.9k
    }
667
36.1k
    if (_format == FileFormat::ORC) {
668
30.1k
        *reader = std::make_unique<format::orc::OrcReader>(
669
30.1k
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
670
30.1k
                _global_rowid_context, enable_mapping_timestamp_tz);
671
30.1k
        return Status::OK();
672
30.1k
    }
673
6.01k
    if (_format == FileFormat::CSV) {
674
951
        if (_file_slot_descs == nullptr) {
675
0
            return Status::InvalidArgument("CSV reader requires file slot descriptors");
676
0
        }
677
        // CSV has no embedded schema. TableReader owns table-level mapping, while CsvReader needs
678
        // only the physical file slots plus scan text parameters to build a file-local schema.
679
        // Non-file columns such as partitions/defaults/virtual row ids are intentionally excluded
680
        // from `_file_slot_descs` and are materialized during finalize_chunk().
681
951
        *reader = std::make_unique<format::csv::CsvReader>(
682
951
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
683
951
                _scan_params, *_file_slot_descs, _current_range_compress_type,
684
951
                _current_range_load_id);
685
951
        return Status::OK();
686
951
    }
687
5.06k
    if (_format == FileFormat::TEXT) {
688
4.56k
        if (_file_slot_descs == nullptr) {
689
0
            return Status::InvalidArgument("Text reader requires file slot descriptors");
690
0
        }
691
        // Text files have no embedded schema. As with CSV, TableReader handles table-level mapping
692
        // and only passes physical file slots to the v2 TextReader.
693
4.56k
        *reader = std::make_unique<format::text::TextReader>(
694
4.56k
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
695
4.56k
                _scan_params, *_file_slot_descs, _current_range_compress_type,
696
4.56k
                _current_range_load_id);
697
4.56k
        return Status::OK();
698
4.56k
    }
699
582
    if (_format == FileFormat::JSON) {
700
582
        if (_file_slot_descs == nullptr) {
701
0
            return Status::InvalidArgument("JSON reader requires file slot descriptors");
702
0
        }
703
582
        *reader = std::make_unique<format::json::JsonReader>(
704
582
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
705
582
                _scan_params, _current_file_range_desc, *_file_slot_descs,
706
582
                _current_range_compress_type, _current_range_load_id);
707
582
        return Status::OK();
708
582
    }
709
18.4E
    if (_format == FileFormat::NATIVE) {
710
2
        *reader = std::make_unique<format::native::NativeReader>(
711
2
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile);
712
2
        return Status::OK();
713
2
    }
714
18.4E
    return Status::NotSupported("TableReader does not support file format {}",
715
18.4E
                                file_format_to_string(_format));
716
18.4E
}
717
718
123k
std::unique_ptr<io::FileDescription> create_file_description(const TFileRangeDesc& range) {
719
123k
    auto file_description = std::make_unique<io::FileDescription>();
720
123k
    file_description->path = range.path;
721
18.4E
    file_description->file_size = range.__isset.file_size ? range.file_size : -1;
722
123k
    file_description->mtime = range.__isset.modification_time ? range.modification_time : 0;
723
123k
    file_description->range_start_offset = range.__isset.start_offset ? range.start_offset : 0;
724
123k
    file_description->range_size = range.__isset.size ? range.size : -1;
725
123k
    if (range.__isset.fs_name) {
726
87.8k
        file_description->fs_name = range.fs_name;
727
87.8k
    }
728
123k
    if (range.__isset.file_cache_admission) {
729
123k
        file_description->file_cache_admission = range.file_cache_admission;
730
123k
    }
731
123k
    return file_description;
732
123k
}
733
734
123k
Status TableReader::prepare_split(const SplitReadOptions& options) {
735
123k
    SCOPED_TIMER(_profile.prepare_split_timer);
736
    // Update to current split format to handle ORC/PARQUET files in one table.
737
123k
    _format = options.current_split_format;
738
123k
    _partition_values = std::move(options.partition_values);
739
123k
    _current_task = std::make_unique<ScanTask>();
740
123k
    _current_task->data_file = create_file_description(options.current_range);
741
123k
    _current_file_description = *_current_task->data_file;
742
123k
    _current_file_range_desc = options.current_range;
743
123k
    _current_range_compress_type = options.current_range.__isset.compress_type
744
123k
                                           ? options.current_range.compress_type
745
123k
                                           : TFileCompressType::UNKNOWN;
746
123k
    _current_range_load_id = options.current_range.__isset.load_id
747
123k
                                     ? std::make_optional(options.current_range.load_id)
748
123k
                                     : std::nullopt;
749
123k
    _global_rowid_context = options.global_rowid_context;
750
123k
    _delete_rows = nullptr;
751
123k
    _aggregate_pushdown_tried = false;
752
123k
    _remaining_table_level_count = -1;
753
123k
    _current_reader_reached_eof = false;
754
123k
    if (_push_down_agg_type == TPushAggOp::type::COUNT &&
755
123k
        options.current_range.__isset.table_format_params &&
756
123k
        options.current_range.table_format_params.__isset.table_level_row_count) {
757
2.62k
        DORIS_CHECK(options.current_range.table_format_params.table_level_row_count >= -1);
758
2.62k
        _remaining_table_level_count =
759
2.62k
                options.current_range.table_format_params.table_level_row_count;
760
2.62k
    }
761
123k
    if (_is_table_level_count_active()) {
762
214
        return Status::OK();
763
214
    }
764
123k
    return _parse_delete_predicates(options);
765
123k
}
766
767
123k
Status TableReader::_parse_delete_predicates(const SplitReadOptions& options) {
768
123k
    DeleteFileDesc desc {.fs_name = options.current_range.fs_name};
769
123k
    bool has_delete_file = false;
770
123k
    RETURN_IF_ERROR(_parse_deletion_vector_file(options.current_range.table_format_params, &desc,
771
123k
                                                &has_delete_file));
772
123k
    if (has_delete_file) {
773
25.2k
        DORIS_CHECK(options.cache != nullptr);
774
25.2k
        Status create_status = Status::OK();
775
776
25.2k
        _delete_rows = options.cache->get<DeleteRows>(desc.key, [&]() -> DeleteRows* {
777
1.67k
            auto delete_rows = std::make_unique<DeleteRows>();
778
779
1.67k
            DeletionVectorReader dv_reader(_runtime_state, _scanner_profile, *_scan_params, desc,
780
1.67k
                                           _io_ctx.get());
781
1.67k
            create_status = dv_reader.open();
782
1.67k
            if (!create_status.ok()) [[unlikely]] {
783
0
                return nullptr;
784
0
            }
785
786
1.67k
            size_t bytes_read = desc.size;
787
1.67k
            std::vector<char> buffer(bytes_read);
788
1.67k
            DBUG_EXECUTE_IF("TableReader.parse_deletion_vector.io_error", {
789
1.67k
                create_status = Status::IOError("injected format v2 deletion vector read failure");
790
1.67k
                return nullptr;
791
1.67k
            });
792
1.66k
            DBUG_EXECUTE_IF("TableReader.parse_deletion_vector.should_stop", {
793
1.66k
                create_status = Status::EndOfFile("stop read.");
794
1.66k
                return nullptr;
795
1.66k
            });
796
1.66k
            create_status = dv_reader.read_at(desc.start_offset, {buffer.data(), bytes_read});
797
1.66k
            if (!create_status.ok()) [[unlikely]] {
798
0
                return nullptr;
799
0
            }
800
801
1.66k
            const char* buf = buffer.data();
802
1.66k
            SCOPED_TIMER(_profile.parse_delete_file_time);
803
1.66k
            create_status = parse_deletion_vector(buf, bytes_read, desc.format, delete_rows.get());
804
1.66k
            if (!create_status.ok()) [[unlikely]] {
805
1
                return nullptr;
806
1
            }
807
1.66k
            COUNTER_UPDATE(_profile.num_delete_rows, delete_rows->size());
808
1.66k
            return delete_rows.release();
809
1.66k
        });
810
25.2k
        RETURN_IF_ERROR(create_status);
811
25.2k
    }
812
813
123k
    return Status::OK();
814
123k
}
815
} // namespace doris::format