Coverage Report

Created: 2026-07-08 04:30

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
1.02M
const schema::external::TField* get_field_ptr(const schema::external::TFieldPtr& field_ptr) {
136
1.02M
    if (!field_ptr.__isset.field_ptr || field_ptr.field_ptr == nullptr) {
137
0
        return nullptr;
138
0
    }
139
1.02M
    return field_ptr.field_ptr.get();
140
1.02M
}
141
142
1.02M
bool external_field_matches_name(const schema::external::TField& field, const std::string& name) {
143
1.02M
    if (field.__isset.name && to_lower(field.name) == to_lower(name)) {
144
73.5k
        return true;
145
73.5k
    }
146
947k
    return field.__isset.name_mapping &&
147
947k
           std::ranges::any_of(field.name_mapping, [&](const std::string& alias) {
148
16
               return to_lower(alias) == to_lower(name);
149
16
           });
150
1.02M
}
151
152
DataTypePtr find_struct_child_type_by_external_field(const DataTypeStruct& struct_type,
153
15.3k
                                                     const schema::external::TField& field) {
154
35.1k
    for (size_t field_idx = 0; field_idx < struct_type.get_elements().size(); ++field_idx) {
155
35.1k
        if (external_field_matches_name(field, struct_type.get_element_name(field_idx))) {
156
15.3k
            return struct_type.get_element(field_idx);
157
15.3k
        }
158
35.1k
    }
159
0
    return nullptr;
160
15.3k
}
161
162
ColumnDefinition build_schema_column_from_external_field(const schema::external::TField& field,
163
97.1k
                                                         DataTypePtr type) {
164
97.1k
    ColumnDefinition column {
165
18.4E
            .identifier = field.__isset.id ? Field::create_field<TYPE_INT>(field.id) : Field {},
166
97.1k
            .name = field.__isset.name ? field.name : "",
167
97.1k
            .name_mapping =
168
97.1k
                    field.__isset.name_mapping ? field.name_mapping : std::vector<std::string> {},
169
97.1k
            .type = std::move(type),
170
97.1k
            .children = {},
171
97.1k
            .default_expr = nullptr,
172
97.1k
            .is_partition_key = false,
173
97.1k
    };
174
97.1k
    if (column.type == nullptr || !field.__isset.nestedField) {
175
75.5k
        return column;
176
75.5k
    }
177
178
21.5k
    const auto nested_type = remove_nullable(column.type);
179
21.5k
    switch (nested_type->get_primitive_type()) {
180
6.48k
    case TYPE_STRUCT: {
181
6.48k
        if (!field.nestedField.__isset.struct_field ||
182
6.48k
            !field.nestedField.struct_field.__isset.fields) {
183
0
            return column;
184
0
        }
185
6.48k
        const auto& struct_type = assert_cast<const DataTypeStruct&>(*nested_type);
186
15.3k
        for (const auto& child_ptr : field.nestedField.struct_field.fields) {
187
15.3k
            const auto* child_field = get_field_ptr(child_ptr);
188
15.3k
            if (child_field == nullptr || !child_field->__isset.name) {
189
0
                continue;
190
0
            }
191
15.3k
            auto child_type = find_struct_child_type_by_external_field(struct_type, *child_field);
192
15.3k
            if (child_type == nullptr) {
193
0
                continue;
194
0
            }
195
15.3k
            column.children.push_back(
196
15.3k
                    build_schema_column_from_external_field(*child_field, child_type));
197
15.3k
        }
198
6.48k
        break;
199
6.48k
    }
200
6.66k
    case TYPE_ARRAY: {
201
6.66k
        if (!field.nestedField.__isset.array_field ||
202
6.66k
            !field.nestedField.array_field.__isset.item_field) {
203
0
            return column;
204
0
        }
205
6.66k
        const auto* item_field = get_field_ptr(field.nestedField.array_field.item_field);
206
6.66k
        if (item_field == nullptr) {
207
0
            return column;
208
0
        }
209
6.66k
        const auto& array_type = assert_cast<const DataTypeArray&>(*nested_type);
210
6.66k
        auto child =
211
6.66k
                build_schema_column_from_external_field(*item_field, array_type.get_nested_type());
212
6.66k
        child.name = "element";
213
6.66k
        if (child.has_identifier_name()) {
214
0
            child.identifier = Field::create_field<TYPE_STRING>(child.name);
215
0
        }
216
6.66k
        column.children.push_back(std::move(child));
217
6.66k
        break;
218
6.66k
    }
219
8.43k
    case TYPE_MAP: {
220
8.43k
        if (!field.nestedField.__isset.map_field ||
221
8.43k
            !field.nestedField.map_field.__isset.key_field ||
222
8.43k
            !field.nestedField.map_field.__isset.value_field) {
223
0
            return column;
224
0
        }
225
8.43k
        const auto& map_type = assert_cast<const DataTypeMap&>(*nested_type);
226
8.43k
        const auto* key_field = get_field_ptr(field.nestedField.map_field.key_field);
227
8.43k
        if (key_field != nullptr) {
228
8.43k
            auto child =
229
8.43k
                    build_schema_column_from_external_field(*key_field, map_type.get_key_type());
230
8.43k
            child.name = "key";
231
8.43k
            if (child.has_identifier_name()) {
232
0
                child.identifier = Field::create_field<TYPE_STRING>(child.name);
233
0
            }
234
8.43k
            column.children.push_back(std::move(child));
235
8.43k
        }
236
8.43k
        const auto* value_field = get_field_ptr(field.nestedField.map_field.value_field);
237
8.43k
        if (value_field != nullptr) {
238
8.43k
            auto child = build_schema_column_from_external_field(*value_field,
239
8.43k
                                                                 map_type.get_value_type());
240
8.43k
            child.name = "value";
241
8.43k
            if (child.has_identifier_name()) {
242
0
                child.identifier = Field::create_field<TYPE_STRING>(child.name);
243
0
            }
244
8.43k
            column.children.push_back(std::move(child));
245
8.43k
        }
246
8.43k
        break;
247
8.43k
    }
248
0
    default:
249
0
        break;
250
21.5k
    }
251
21.5k
    return column;
252
21.5k
}
253
254
const schema::external::TField* find_external_root_field(const TFileScanRangeParams* params,
255
212k
                                                         const ColumnDefinition& column) {
256
212k
    if (params == nullptr || !params->__isset.history_schema_info ||
257
212k
        params->history_schema_info.empty()) {
258
154k
        return nullptr;
259
154k
    }
260
58.3k
    const auto* schema = &params->history_schema_info.front();
261
58.3k
    if (params->__isset.current_schema_id) {
262
58.3k
        for (const auto& candidate_schema : params->history_schema_info) {
263
58.3k
            if (candidate_schema.__isset.schema_id &&
264
58.3k
                candidate_schema.schema_id == params->current_schema_id) {
265
58.3k
                schema = &candidate_schema;
266
58.3k
                break;
267
58.3k
            }
268
58.3k
        }
269
58.3k
    }
270
58.3k
    if (!schema->__isset.root_field || !schema->root_field.__isset.fields) {
271
0
        return nullptr;
272
0
    }
273
986k
    for (const auto& field_ptr : schema->root_field.fields) {
274
986k
        const auto* field = get_field_ptr(field_ptr);
275
986k
        if (field == nullptr) {
276
0
            continue;
277
0
        }
278
986k
        if (external_field_matches_name(*field, column.name)) {
279
58.2k
            return field;
280
58.2k
        }
281
986k
    }
282
150
    return nullptr;
283
58.3k
}
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
5.04k
bool contains_runtime_filter(const VExprContextSPtrs& conjuncts) {
311
5.50k
    return std::ranges::any_of(conjuncts, [](const auto& conjunct) {
312
5.50k
        return conjunct != nullptr && conjunct->root() != nullptr &&
313
5.50k
               conjunct->root()->is_rf_wrapper();
314
5.50k
    });
315
5.04k
}
316
317
82.9k
void collect_global_indices(const VExprSPtr& expr, std::set<GlobalIndex>* global_indices) {
318
82.9k
    if (expr == nullptr) {
319
0
        return;
320
0
    }
321
82.9k
    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
7.03k
        collect_global_indices(expr->get_impl(), global_indices);
326
7.03k
        return;
327
7.03k
    }
328
75.9k
    if (expr->is_slot_ref()) {
329
23.6k
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
330
23.6k
        DORIS_CHECK(slot_ref->column_id() >= 0);
331
23.6k
        global_indices->insert(GlobalIndex(cast_set<size_t>(slot_ref->column_id())));
332
23.6k
    }
333
75.9k
    for (const auto& child : expr->children()) {
334
53.0k
        collect_global_indices(child, global_indices);
335
53.0k
    }
336
75.9k
}
337
338
Status build_table_filters_from_conjunct(const VExprContextSPtr& conjunct, RuntimeState* state,
339
23.0k
                                         std::vector<TableFilter>* table_filters) {
340
23.0k
    if (conjunct == nullptr) {
341
0
        return Status::OK();
342
0
    }
343
23.0k
    std::set<GlobalIndex> global_indices;
344
23.0k
    collect_global_indices(conjunct->root(), &global_indices);
345
23.0k
    if (!global_indices.empty()) {
346
23.0k
        TableFilter table_filter;
347
23.0k
        VExprSPtr filter_root;
348
23.0k
        RETURN_IF_ERROR(clone_table_expr_tree(conjunct->root(), &filter_root));
349
23.0k
        table_filter.conjunct = VExprContext::create_shared(std::move(filter_root));
350
23.6k
        for (const auto global_index : global_indices) {
351
23.6k
            table_filter.global_indices.push_back(global_index);
352
23.6k
        }
353
23.0k
        table_filters->push_back(std::move(table_filter));
354
23.0k
    }
355
23.0k
    return Status::OK();
356
23.0k
}
357
358
Status parse_deletion_vector(const char* buf, size_t buffer_size, DeleteFileDesc::Format format,
359
960
                             DeleteRows* delete_rows) {
360
960
    DORIS_CHECK(buf != nullptr);
361
960
    DORIS_CHECK(delete_rows != nullptr);
362
960
    DORIS_CHECK(format == DeleteFileDesc::Format::PAIMON ||
363
960
                format == DeleteFileDesc::Format::ICEBERG);
364
365
960
    const size_t checksum_size = format == DeleteFileDesc::Format::ICEBERG ? 4 : 0;
366
960
    if (buffer_size < 8 + checksum_size) [[unlikely]] {
367
0
        return Status::DataQualityError("Deletion vector file size too small: {}", buffer_size);
368
0
    }
369
370
960
    auto total_length = BigEndian::Load32(buf);
371
960
    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
960
    const char* bitmap_buf = buf + 8;
377
960
    const size_t bitmap_size = buffer_size - 8 - checksum_size;
378
960
    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
29
        constexpr static char PAIMON_BITMAP_MAGIC[] = {'\x5E', '\x43', '\xF2', '\xD0'};
383
29
        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
29
        roaring::Roaring bitmap;
391
29
        try {
392
29
            bitmap = roaring::Roaring::readSafe(bitmap_buf, bitmap_size);
393
29
        } catch (const std::runtime_error& e) {
394
0
            return Status::DataQualityError("Decode roaring bitmap failed, {}", e.what());
395
0
        }
396
397
29
        delete_rows->reserve(bitmap.cardinality());
398
59
        for (auto it = bitmap.begin(); it != bitmap.end(); it++) {
399
30
            delete_rows->push_back(*it);
400
30
        }
401
29
        return Status::OK();
402
29
    }
403
404
931
    constexpr static char ICEBERG_DV_MAGIC[] = {'\xD1', '\xD3', '\x39', '\x64'};
405
931
    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
931
    roaring::Roaring64Map bitmap;
412
931
    try {
413
931
        bitmap = roaring::Roaring64Map::readSafe(bitmap_buf, bitmap_size);
414
931
    } catch (const std::runtime_error& e) {
415
0
        return Status::DataQualityError("Decode roaring bitmap failed, {}", e.what());
416
0
    }
417
418
931
    delete_rows->reserve(bitmap.cardinality());
419
5.22M
    for (auto it = bitmap.begin(); it != bitmap.end(); it++) {
420
5.22M
        delete_rows->push_back(cast_set<int64_t>(*it));
421
5.22M
    }
422
931
    return Status::OK();
423
931
}
424
425
} // namespace
426
427
std::shared_ptr<io::FileSystemProperties> create_system_properties(
428
37.4k
        const TFileScanRangeParams* scan_params) {
429
37.4k
    auto system_properties = std::make_shared<io::FileSystemProperties>();
430
37.4k
    if (scan_params == nullptr || !scan_params->__isset.file_type) {
431
6.59k
        system_properties->system_type = TFileType::FILE_LOCAL;
432
6.59k
        return system_properties;
433
6.59k
    }
434
30.8k
    system_properties->system_type = scan_params->file_type;
435
30.8k
    system_properties->properties = scan_params->properties;
436
30.8k
    system_properties->hdfs_params = scan_params->hdfs_params;
437
30.8k
    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
30.8k
    return system_properties;
442
37.4k
}
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
212k
                                              ColumnDefinition* column) const {
501
212k
    (void)slot_info;
502
212k
    DORIS_CHECK(context != nullptr);
503
212k
    DORIS_CHECK(column != nullptr);
504
212k
    context->schema_column.reset();
505
212k
    const auto* schema_field = find_external_root_field(context->scan_params, *column);
506
212k
    if (schema_field == nullptr) {
507
154k
        return Status::OK();
508
154k
    }
509
58.2k
    context->schema_column = build_schema_column_from_external_field(*schema_field, column->type);
510
58.2k
    column->identifier = context->schema_column->identifier;
511
58.2k
    column->name_mapping = context->schema_column->name_mapping;
512
58.2k
    return Status::OK();
513
212k
}
514
515
37.4k
Status TableReader::init(TableReadOptions&& options) {
516
37.4k
    _scan_params = options.scan_params;
517
37.4k
    _format = options.format;
518
37.4k
    _io_ctx = options.io_ctx;
519
37.4k
    _runtime_state = options.runtime_state;
520
37.4k
    _scanner_profile = options.scanner_profile;
521
37.4k
    _file_slot_descs = options.file_slot_descs;
522
37.4k
    _push_down_agg_type = options.push_down_agg_type;
523
37.4k
    _condition_cache_digest = options.condition_cache_digest;
524
37.4k
    _projected_columns = std::move(options.projected_columns);
525
37.4k
    _system_properties = create_system_properties(_scan_params);
526
37.4k
    _mapper_options.mode = TableColumnMappingMode::BY_NAME;
527
37.4k
    _conjuncts = std::move(options.conjuncts);
528
529
37.4k
    if (_scanner_profile != nullptr) {
530
37.3k
        static const char* table_profile = "TableReader";
531
37.3k
        ADD_TIMER_WITH_LEVEL(_scanner_profile, table_profile, 1);
532
37.3k
        _profile.num_delete_files = ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "NumDeleteFiles",
533
37.3k
                                                                 TUnit::UNIT, table_profile, 1);
534
37.3k
        _profile.num_delete_rows = ADD_CHILD_COUNTER_WITH_LEVEL(_scanner_profile, "NumDeleteRows",
535
37.3k
                                                                TUnit::UNIT, table_profile, 1);
536
37.3k
        _profile.parse_delete_file_time = ADD_CHILD_TIMER_WITH_LEVEL(
537
37.3k
                _scanner_profile, "ParseDeleteFileTime", table_profile, 1);
538
37.3k
        _profile.exec_timer =
539
37.3k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "GetBlockTime", table_profile, 1);
540
37.3k
        _profile.prepare_split_timer =
541
37.3k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "PrepareSplitTime", table_profile, 1);
542
37.3k
        _profile.finalize_timer =
543
37.3k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "FinalizeBlockTime", table_profile, 1);
544
37.3k
        _profile.create_reader_timer =
545
37.3k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "CreateReaderTime", table_profile, 1);
546
37.3k
        _profile.pushdown_agg_timer =
547
37.3k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "PushDownAggTime", table_profile, 1);
548
37.3k
        _profile.open_reader_timer =
549
37.3k
                ADD_CHILD_TIMER_WITH_LEVEL(_scanner_profile, "OpenReaderTime", table_profile, 1);
550
37.3k
    }
551
37.4k
    return Status::OK();
552
37.4k
}
553
554
39.1k
Status TableReader::_build_table_filters_from_conjuncts() {
555
39.1k
    _table_filters.clear();
556
39.1k
    for (const auto& conjunct : _conjuncts) {
557
23.0k
        RETURN_IF_ERROR(
558
23.0k
                build_table_filters_from_conjunct(conjunct, _runtime_state, &_table_filters));
559
23.0k
    }
560
39.1k
    return Status::OK();
561
39.1k
}
562
563
38.4k
Status TableReader::_open_local_filter_exprs(const FileScanRequest& file_request) {
564
38.4k
    RowDescriptor row_desc;
565
38.4k
    for (const auto& conjunct : file_request.conjuncts) {
566
15.3k
        RETURN_IF_ERROR(conjunct->prepare(_runtime_state, row_desc));
567
15.3k
        RETURN_IF_ERROR(conjunct->open(_runtime_state));
568
15.3k
    }
569
38.4k
    for (const auto& delete_conjunct : file_request.delete_conjuncts) {
570
4.47k
        RETURN_IF_ERROR(delete_conjunct->prepare(_runtime_state, row_desc));
571
4.47k
        RETURN_IF_ERROR(delete_conjunct->open(_runtime_state));
572
4.47k
    }
573
38.4k
    return Status::OK();
574
38.4k
}
575
576
38.5k
bool TableReader::_should_enable_condition_cache(const FileScanRequest& file_request) const {
577
38.5k
    if (_condition_cache_digest == 0 || _push_down_agg_type == TPushAggOp::type::COUNT ||
578
38.5k
        _current_file_description == std::nullopt || _data_reader.reader == nullptr) {
579
6.43k
        return false;
580
6.43k
    }
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
32.0k
    if (file_request.conjuncts.empty()) {
585
25.1k
        return false;
586
25.1k
    }
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
6.91k
    if (_delete_rows != nullptr || !file_request.delete_conjuncts.empty()) {
591
1.82k
        return false;
592
1.82k
    }
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
5.09k
    return !contains_runtime_filter(file_request.conjuncts);
597
6.91k
}
598
599
38.4k
Status TableReader::_init_reader_condition_cache(const FileScanRequest& file_request) {
600
38.4k
    _condition_cache = nullptr;
601
38.4k
    _condition_cache_ctx = nullptr;
602
38.4k
    if (!_should_enable_condition_cache(file_request)) {
603
34.3k
        return Status::OK();
604
34.3k
    }
605
606
4.07k
    auto* cache = segment_v2::ConditionCache::instance();
607
4.07k
    if (cache == nullptr) {
608
0
        return Status::OK();
609
0
    }
610
4.07k
    const auto& file = *_current_file_description;
611
4.07k
    _condition_cache_key = segment_v2::ConditionCache::ExternalCacheKey(
612
4.07k
            file.path, file.mtime, file.file_size, _condition_cache_digest, file.range_start_offset,
613
4.07k
            file.range_size);
614
615
4.07k
    segment_v2::ConditionCacheHandle handle;
616
4.07k
    const bool condition_cache_hit = cache->lookup(_condition_cache_key, &handle);
617
4.07k
    if (condition_cache_hit) {
618
1.11k
        _condition_cache = handle.get_filter_result();
619
1.11k
        ++_condition_cache_hit_count;
620
2.95k
    } else {
621
2.95k
        const int64_t total_rows = _data_reader.reader->get_total_rows();
622
2.95k
        if (total_rows <= 0) {
623
909
            return Status::OK();
624
909
        }
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.04k
        const size_t num_granules = (total_rows + ConditionCacheContext::GRANULE_SIZE - 1) /
629
2.04k
                                    ConditionCacheContext::GRANULE_SIZE;
630
2.04k
        _condition_cache = std::make_shared<std::vector<bool>>(num_granules + 1, false);
631
2.04k
    }
632
633
3.16k
    if (_condition_cache != nullptr) {
634
3.13k
        _condition_cache_ctx = std::make_shared<ConditionCacheContext>();
635
3.13k
        _condition_cache_ctx->is_hit = condition_cache_hit;
636
3.13k
        _condition_cache_ctx->filter_result = _condition_cache;
637
3.13k
        _data_reader.reader->set_condition_cache_context(_condition_cache_ctx);
638
3.13k
    }
639
3.16k
    return Status::OK();
640
4.07k
}
641
642
39.3k
void TableReader::_finalize_reader_condition_cache() {
643
39.3k
    if (_condition_cache_ctx == nullptr || _condition_cache_ctx->is_hit) {
644
37.3k
        _condition_cache = nullptr;
645
37.3k
        _condition_cache_ctx = nullptr;
646
37.3k
        return;
647
37.3k
    }
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.01k
    if (!_current_reader_reached_eof) {
652
55
        _condition_cache = nullptr;
653
55
        _condition_cache_ctx = nullptr;
654
55
        return;
655
55
    }
656
1.96k
    segment_v2::ConditionCache::instance()->insert(_condition_cache_key,
657
1.96k
                                                   std::move(_condition_cache));
658
1.96k
    _condition_cache = nullptr;
659
1.96k
    _condition_cache_ctx = nullptr;
660
1.96k
}
661
662
77.2k
Status TableReader::create_next_reader(bool* eos) {
663
77.2k
    SCOPED_TIMER(_profile.create_reader_timer);
664
77.2k
    DCHECK(_data_reader.reader == nullptr);
665
77.2k
    if (_current_task == nullptr) {
666
37.9k
        *eos = true;
667
37.9k
        return Status::OK();
668
37.9k
    }
669
670
39.2k
    RETURN_IF_ERROR(create_file_reader(&_data_reader.reader));
671
39.2k
    DORIS_CHECK(_data_reader.reader != nullptr);
672
39.2k
    if (_batch_size > 0) {
673
34.9k
        _data_reader.reader->set_batch_size(_batch_size);
674
34.9k
    }
675
39.2k
    Status st = _data_reader.reader->init(_runtime_state);
676
39.2k
    if (!st.ok()) {
677
14
        if (_io_ctx != nullptr && _io_ctx->should_stop && st.is<ErrorCode::END_OF_FILE>()) {
678
0
            *eos = true;
679
0
            _data_reader.reader.reset();
680
0
            return Status::OK();
681
0
        }
682
14
        return st;
683
14
    }
684
39.2k
    st = open_reader();
685
39.2k
    if (!st.ok()) {
686
0
        if (_io_ctx != nullptr && _io_ctx->should_stop && st.is<ErrorCode::END_OF_FILE>()) {
687
0
            *eos = true;
688
0
            _data_reader.reader.reset();
689
0
            return Status::OK();
690
0
        }
691
0
        return st;
692
0
    }
693
39.2k
    if (_data_reader.reader == nullptr) {
694
735
        *eos = _current_task == nullptr;
695
735
        return Status::OK();
696
735
    }
697
38.4k
    *eos = false;
698
38.4k
    return Status::OK();
699
39.2k
}
700
701
39.1k
Status TableReader::create_file_reader(std::unique_ptr<FileReader>* reader) {
702
39.1k
    DORIS_CHECK(reader != nullptr);
703
39.1k
    if (_format == FileFormat::PARQUET) {
704
33.0k
        const bool enable_mapping_timestamp_tz =
705
33.0k
                _scan_params != nullptr && _scan_params->__isset.enable_mapping_timestamp_tz &&
706
33.0k
                _scan_params->enable_mapping_timestamp_tz;
707
33.0k
        *reader = std::make_unique<format::parquet::ParquetReader>(
708
33.0k
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
709
33.0k
                _global_rowid_context, enable_mapping_timestamp_tz);
710
33.0k
        return Status::OK();
711
33.0k
    }
712
6.08k
    if (_format == FileFormat::CSV) {
713
947
        if (_file_slot_descs == nullptr) {
714
0
            return Status::InvalidArgument("CSV reader requires file slot descriptors");
715
0
        }
716
        // CSV has no embedded schema. TableReader owns table-level mapping, while CsvReader needs
717
        // only the physical file slots plus scan text parameters to build a file-local schema.
718
        // Non-file columns such as partitions/defaults/virtual row ids are intentionally excluded
719
        // from `_file_slot_descs` and are materialized during finalize_chunk().
720
947
        *reader = std::make_unique<format::csv::CsvReader>(
721
947
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
722
947
                _scan_params, *_file_slot_descs, _current_range_compress_type,
723
947
                _current_range_load_id);
724
947
        return Status::OK();
725
947
    }
726
5.13k
    if (_format == FileFormat::TEXT) {
727
4.54k
        if (_file_slot_descs == nullptr) {
728
0
            return Status::InvalidArgument("Text reader requires file slot descriptors");
729
0
        }
730
        // Text files have no embedded schema. As with CSV, TableReader handles table-level mapping
731
        // and only passes physical file slots to the v2 TextReader.
732
4.54k
        *reader = std::make_unique<format::text::TextReader>(
733
4.54k
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
734
4.54k
                _scan_params, *_file_slot_descs, _current_range_compress_type,
735
4.54k
                _current_range_load_id);
736
4.54k
        return Status::OK();
737
4.54k
    }
738
590
    if (_format == FileFormat::JSON) {
739
582
        if (_file_slot_descs == nullptr) {
740
0
            return Status::InvalidArgument("JSON reader requires file slot descriptors");
741
0
        }
742
582
        *reader = std::make_unique<format::json::JsonReader>(
743
582
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile,
744
582
                _scan_params, _current_file_range_desc, *_file_slot_descs,
745
582
                _current_range_compress_type, _current_range_load_id);
746
582
        return Status::OK();
747
582
    }
748
8
    if (_format == FileFormat::NATIVE) {
749
2
        *reader = std::make_unique<format::native::NativeReader>(
750
2
                _system_properties, _current_task->data_file, _io_ctx, _scanner_profile);
751
2
        return Status::OK();
752
2
    }
753
6
    return Status::NotSupported("TableReader does not support file format {}",
754
6
                                file_format_to_string(_format));
755
8
}
756
757
44.5k
std::unique_ptr<io::FileDescription> create_file_description(const TFileRangeDesc& range) {
758
44.5k
    auto file_description = std::make_unique<io::FileDescription>();
759
44.5k
    file_description->path = range.path;
760
44.5k
    file_description->file_size = range.__isset.file_size ? range.file_size : -1;
761
44.5k
    file_description->mtime = range.__isset.modification_time ? range.modification_time : 0;
762
44.5k
    file_description->range_start_offset = range.__isset.start_offset ? range.start_offset : 0;
763
44.5k
    file_description->range_size = range.__isset.size ? range.size : -1;
764
44.5k
    if (range.__isset.fs_name) {
765
17.4k
        file_description->fs_name = range.fs_name;
766
17.4k
    }
767
44.5k
    if (range.__isset.file_cache_admission) {
768
44.3k
        file_description->file_cache_admission = range.file_cache_admission;
769
44.3k
    }
770
44.5k
    return file_description;
771
44.5k
}
772
773
44.5k
Status TableReader::prepare_split(const SplitReadOptions& options) {
774
44.5k
    SCOPED_TIMER(_profile.prepare_split_timer);
775
    // Update to current split format to handle ORC/PARQUET files in one table.
776
44.5k
    _format = options.current_split_format;
777
44.5k
    _partition_values = std::move(options.partition_values);
778
44.5k
    _current_task = std::make_unique<ScanTask>();
779
44.5k
    _current_task->data_file = create_file_description(options.current_range);
780
44.5k
    _current_file_description = *_current_task->data_file;
781
44.5k
    _current_file_range_desc = options.current_range;
782
44.5k
    _current_range_compress_type = options.current_range.__isset.compress_type
783
44.5k
                                           ? options.current_range.compress_type
784
44.5k
                                           : TFileCompressType::UNKNOWN;
785
44.5k
    _current_range_load_id = options.current_range.__isset.load_id
786
44.5k
                                     ? std::make_optional(options.current_range.load_id)
787
44.5k
                                     : std::nullopt;
788
44.5k
    _global_rowid_context = options.global_rowid_context;
789
44.5k
    _delete_rows = nullptr;
790
44.5k
    _aggregate_pushdown_tried = false;
791
44.5k
    _remaining_table_level_count = -1;
792
44.5k
    _current_reader_reached_eof = false;
793
44.5k
    if (_push_down_agg_type == TPushAggOp::type::COUNT &&
794
44.5k
        options.current_range.__isset.table_format_params &&
795
44.5k
        options.current_range.table_format_params.__isset.table_level_row_count) {
796
2.15k
        DORIS_CHECK(options.current_range.table_format_params.table_level_row_count >= -1);
797
2.15k
        _remaining_table_level_count =
798
2.15k
                options.current_range.table_format_params.table_level_row_count;
799
2.15k
    }
800
44.5k
    if (_is_table_level_count_active()) {
801
182
        return Status::OK();
802
182
    }
803
44.3k
    return _parse_delete_predicates(options);
804
44.5k
}
805
806
44.3k
Status TableReader::_parse_delete_predicates(const SplitReadOptions& options) {
807
44.3k
    DeleteFileDesc desc {.fs_name = options.current_range.fs_name};
808
44.3k
    bool has_delete_file = false;
809
44.3k
    RETURN_IF_ERROR(_parse_deletion_vector_file(options.current_range.table_format_params, &desc,
810
44.3k
                                                &has_delete_file));
811
44.3k
    if (has_delete_file) {
812
2.43k
        DORIS_CHECK(options.cache != nullptr);
813
2.43k
        Status create_status = Status::OK();
814
815
2.43k
        _delete_rows = options.cache->get<DeleteRows>(desc.key, [&]() -> DeleteRows* {
816
960
            auto* delete_rows = new DeleteRows;
817
818
960
            DeletionVectorReader dv_reader(_runtime_state, _scanner_profile, *_scan_params, desc,
819
960
                                           _io_ctx.get());
820
960
            create_status = dv_reader.open();
821
960
            if (!create_status.ok()) [[unlikely]] {
822
0
                return nullptr;
823
0
            }
824
825
960
            size_t bytes_read = desc.size;
826
960
            std::vector<char> buffer(bytes_read);
827
960
            create_status = dv_reader.read_at(desc.start_offset, {buffer.data(), bytes_read});
828
960
            if (!create_status.ok()) [[unlikely]] {
829
0
                return nullptr;
830
0
            }
831
832
960
            const char* buf = buffer.data();
833
960
            SCOPED_TIMER(_profile.parse_delete_file_time);
834
960
            create_status = parse_deletion_vector(buf, bytes_read, desc.format, delete_rows);
835
960
            if (!create_status.ok()) [[unlikely]] {
836
0
                return nullptr;
837
0
            }
838
960
            COUNTER_UPDATE(_profile.num_delete_rows, delete_rows->size());
839
960
            return delete_rows;
840
960
        });
841
2.43k
        RETURN_IF_ERROR(create_status);
842
2.43k
    }
843
844
44.3k
    return Status::OK();
845
44.3k
}
846
} // namespace doris::format