Coverage Report

Created: 2026-07-06 18:44

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