Coverage Report

Created: 2026-07-07 01:02

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