Coverage Report

Created: 2026-08-20 19:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format_v2/file_reader.h
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
//   http://www.apache.org/licenses/LICENSE-2.0
9
// Unless required by applicable law or agreed to in writing,
10
// software distributed under the License is distributed on an
11
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
12
// KIND, either express or implied.  See the License for the
13
// specific language governing permissions and limitations
14
// under the License.
15
16
#pragma once
17
18
#include <algorithm>
19
#include <cstddef>
20
#include <cstdint>
21
#include <limits>
22
#include <map>
23
#include <memory>
24
#include <string>
25
#include <utility>
26
#include <vector>
27
28
#include "common/cast_set.h"
29
#include "common/status.h"
30
#include "core/data_type/data_type.h"
31
#include "core/field.h"
32
#include "exprs/vexpr_fwd.h"
33
#include "format_v2/column_data.h"
34
#include "gen_cpp/PlanNodes_types.h"
35
#include "io/file_factory.h"
36
#include "io/fs/file_reader_writer_fwd.h"
37
#include "io/io_common.h"
38
39
namespace doris {
40
class Block;
41
struct ConditionCacheContext;
42
43
namespace io {
44
struct IOContext;
45
} // namespace io
46
} // namespace doris
47
48
namespace doris::format {
49
50
class TableColumnMapper;
51
struct TableColumnMapperOptions;
52
53
enum class FileFormat {
54
    PARQUET,
55
    ORC,
56
    CSV,
57
    JSON,
58
    TEXT,
59
    JNI,
60
    NATIVE,
61
    ARROW,
62
    WAL,
63
};
64
65
struct FileScanRequest {
66
802
    virtual ~FileScanRequest() = default;
67
68
    std::string debug_string() const;
69
70
    // Columns that must be read before row-level filtering. They are materialized eagerly because
71
    // conjuncts/delete_conjuncts need them to decide the selected rows.
72
    std::vector<LocalColumnIndex> predicate_columns;
73
    // Columns read after row-level filtering. A complex root may intentionally also appear in
74
    // predicate_columns when its eager predicate subtree is smaller than its final output subtree.
75
    std::vector<LocalColumnIndex> non_predicate_columns;
76
    // Predicate columns introduced only to evaluate hidden filter slots. Their values are dead
77
    // after all file-local predicates run, although the shared file block still needs row-shaped
78
    // placeholders until TableReader finalizes projected columns.
79
    std::vector<LocalColumnId> predicate_only_columns;
80
    // file-local column id -> file-local output block position.
81
    std::map<LocalColumnId, LocalIndex> local_positions;
82
    // Optional output position for a root that has independent eager-predicate and deferred-output
83
    // projections. local_positions continues to identify the position referenced by localized
84
    // predicate expressions.
85
    std::map<LocalColumnId, LocalIndex> non_predicate_positions;
86
    // Row-level filters converted to file-local expressions from table-level predicates.
87
    VExprContextSPtrs conjuncts;
88
    // Only this leading subset may participate in footer/page metadata pruning. The boundary is
89
    // inherited from table-conjunct order so an omitted slotless unsafe expression remains a fence.
90
    size_t metadata_pruning_safe_conjunct_count = std::numeric_limits<size_t>::max();
91
    // Constant split pruning may use only this table-filter prefix after mapping. A rejected
92
    // file-local rewrite is a materialization barrier even when a later filter is constant.
93
    size_t constant_pruning_safe_table_filter_count = std::numeric_limits<size_t>::max();
94
    // Delete predicates converted to file-local expressions. A TRUE result means that the row is
95
    // deleted, so readers must invert each result when building their keep filter.
96
    VExprContextSPtrs delete_conjuncts;
97
    // File-local ids retained only because Nereids keeps a minimum-width output tuple for an
98
    // explicit COUNT(*). These columns have no semantic value: for example, after pruning a scan
99
    // may retain an unsupported TIME_MILLIS leaf even though COUNT(*) only needs one row per
100
    // surviving input row. A reader may synthesize defaults instead of reading a marked column
101
    // while it remains non-predicate. If filters or equality deletes promote the same id to
102
    // predicate_columns, the value is semantically required and must still be validated and read.
103
    std::vector<LocalColumnId> count_star_placeholder_columns;
104
105
    // Table formats may assign semantics that legacy physical files do not encode. Each path here
106
    // identifies an unannotated Parquet group that the physical reader must validate and decode as
107
    // Variant. Keeping this explicit prevents generic Parquet scans from guessing based on names.
108
    std::vector<LocalColumnIndex> variant_schema_overrides;
109
110
2.38k
    bool is_count_star_placeholder(LocalColumnId column_id) const {
111
2.38k
        return std::ranges::find(count_star_placeholder_columns, column_id) !=
112
2.38k
               count_star_placeholder_columns.end();
113
2.38k
    }
114
115
211
    bool is_predicate_only(LocalColumnId column_id) const {
116
211
        return std::ranges::find(predicate_only_columns, column_id) != predicate_only_columns.end();
117
211
    }
118
119
943
    LocalIndex non_predicate_position(LocalColumnId column_id) const {
120
943
        const auto it = non_predicate_positions.find(column_id);
121
943
        return it == non_predicate_positions.end() ? local_positions.at(column_id) : it->second;
122
943
    }
123
124
539
    bool has_deferred_non_predicate_column(LocalColumnId column_id) const {
125
539
        return non_predicate_positions.contains(column_id);
126
539
    }
127
128
156
    size_t block_column_count() const {
129
156
        size_t count = 0;
130
232
        for (const auto& [_, position] : local_positions) {
131
232
            count = std::max(count, position.value() + 1);
132
232
        }
133
156
        for (const auto& [_, position] : non_predicate_positions) {
134
0
            count = std::max(count, position.value() + 1);
135
0
        }
136
156
        return count;
137
156
    }
138
};
139
140
// Helper for constructing the scan-column layout in FileScanRequest.
141
// FileScanRequest keeps predicate and non-predicate columns separate because columnar readers such
142
// as Parquet can read predicate columns first, filter rows, and then lazily read the remaining
143
// projected columns. The two lists still share one file-local output block, whose positions are
144
// stored in local_positions. This builder centralizes the mechanical rules for that shared layout:
145
// - each root file column gets one stable predicate block position;
146
// - predicate columns dominate non-predicate columns because they are already returned in the file
147
//   block and can be reused for final materialization;
148
// - a smaller complex predicate subtree may get a second deferred output position;
149
// - repeated nested projections for the same root are merged instead of duplicated.
150
// TableColumnMapper should still own table-to-file semantic resolution. This helper only owns the
151
// FileScanRequest layout contract after a file-local projection has been produced.
152
class FileScanRequestBuilder {
153
public:
154
523
    explicit FileScanRequestBuilder(FileScanRequest* request) : _request(request) {
155
523
        DORIS_CHECK(_request != nullptr);
156
523
    }
157
158
253
    Status add_predicate_column(LocalColumnIndex projection) {
159
253
        return _add_column(std::move(projection), &_request->predicate_columns,
160
253
                           /*is_predicate_column=*/true);
161
253
    }
162
163
484
    Status add_non_predicate_column(LocalColumnIndex projection) {
164
484
        return _add_column(std::move(projection), &_request->non_predicate_columns,
165
484
                           /*is_predicate_column=*/false);
166
484
    }
167
168
10
    Status add_deferred_non_predicate_column(LocalColumnIndex projection) {
169
10
        const auto file_column_id = projection.column_id();
170
10
        DORIS_CHECK(file_column_id != LocalColumnId::invalid());
171
10
        DORIS_CHECK(_request->local_positions.contains(file_column_id));
172
10
        DORIS_CHECK(std::ranges::any_of(_request->predicate_columns,
173
10
                                        [&](const LocalColumnIndex& predicate) {
174
10
                                            return predicate.column_id() == file_column_id;
175
10
                                        }));
176
177
10
        if (!_request->non_predicate_positions.contains(file_column_id)) {
178
8
            _request->non_predicate_positions.emplace(file_column_id,
179
8
                                                      _next_block_position(*_request));
180
8
        }
181
10
        _sort_projection_children_by_file_id(&projection);
182
10
        auto existing = std::ranges::find_if(_request->non_predicate_columns,
183
10
                                             [&](const LocalColumnIndex& output) {
184
2
                                                 return output.column_id() == file_column_id;
185
2
                                             });
186
10
        if (existing == _request->non_predicate_columns.end()) {
187
10
            _request->non_predicate_columns.push_back(std::move(projection));
188
10
        } else {
189
0
            RETURN_IF_ERROR(merge_local_column_index(&*existing, projection));
190
0
            _sort_projection_children_by_file_id(&*existing);
191
0
        }
192
10
        if (!_request->is_predicate_only(file_column_id)) {
193
            // The eager complex value has a different physical shape from the final value and
194
            // must never leak into table materialization after its predicates have run.
195
10
            _request->predicate_only_columns.push_back(file_column_id);
196
10
        }
197
10
        return Status::OK();
198
10
    }
199
200
153
    Status add_predicate_column(LocalColumnId column_id) {
201
153
        return add_predicate_column(LocalColumnIndex::top_level(column_id));
202
153
    }
203
204
279
    Status add_non_predicate_column(LocalColumnId column_id) {
205
279
        return add_non_predicate_column(LocalColumnIndex::top_level(column_id));
206
279
    }
207
208
private:
209
686
    static LocalIndex _next_block_position(const FileScanRequest& request) {
210
686
        size_t next_position = 0;
211
8.35k
        for (const auto& [_, block_position] : request.local_positions) {
212
8.35k
            next_position = std::max(next_position, block_position.value() + 1);
213
8.35k
        }
214
686
        for (const auto& [_, block_position] : request.non_predicate_positions) {
215
3
            next_position = std::max(next_position, block_position.value() + 1);
216
3
        }
217
686
        return LocalIndex(next_position);
218
686
    }
219
220
854
    static void _sort_projection_children_by_file_id(LocalColumnIndex* projection) {
221
854
        DORIS_CHECK(projection != nullptr);
222
854
        if (projection->project_all_children) {
223
767
            return;
224
767
        }
225
103
        for (auto& child : projection->children) {
226
103
            _sort_projection_children_by_file_id(&child);
227
103
        }
228
87
        std::ranges::sort(projection->children,
229
87
                          [](const LocalColumnIndex& lhs, const LocalColumnIndex& rhs) {
230
30
                              return lhs.local_id() < rhs.local_id();
231
30
                          });
232
87
    }
233
234
    Status _add_column(LocalColumnIndex projection, std::vector<LocalColumnIndex>* scan_columns,
235
737
                       bool is_predicate_column) {
236
737
        DORIS_CHECK(scan_columns != nullptr);
237
737
        const auto file_column_id = projection.column_id();
238
737
        DORIS_CHECK(file_column_id != LocalColumnId::invalid());
239
737
        if (!is_predicate_column &&
240
737
            std::ranges::find_if(_request->predicate_columns,
241
484
                                 [&](const LocalColumnIndex& p) {
242
73
                                     return p.column_id() == file_column_id;
243
73
                                 }) != _request->predicate_columns.end() &&
244
737
            !_request->has_deferred_non_predicate_column(file_column_id)) {
245
2
            return Status::OK();
246
2
        }
247
735
        if (!_request->local_positions.contains(file_column_id)) {
248
678
            _request->local_positions.emplace(file_column_id, _next_block_position(*_request));
249
678
        }
250
251
735
        _sort_projection_children_by_file_id(&projection);
252
735
        auto existing_projection_it = std::ranges::find_if(
253
735
                *scan_columns,
254
8.10k
                [&](const LocalColumnIndex& p) { return p.column_id() == file_column_id; });
255
735
        if (existing_projection_it == scan_columns->end()) {
256
729
            scan_columns->push_back(std::move(projection));
257
729
        } else {
258
6
            RETURN_IF_ERROR(merge_local_column_index(&*existing_projection_it, projection));
259
6
            _sort_projection_children_by_file_id(&*existing_projection_it);
260
6
        }
261
262
735
        if (is_predicate_column && !_request->has_deferred_non_predicate_column(file_column_id)) {
263
250
            auto it = std::ranges::find_if(
264
250
                    _request->non_predicate_columns,
265
250
                    [&](const LocalColumnIndex& p) { return p.column_id() == file_column_id; });
266
250
            if (it != _request->non_predicate_columns.end()) {
267
10
                _request->non_predicate_columns.erase(it);
268
10
            }
269
250
        }
270
735
        return Status::OK();
271
735
    }
272
273
    FileScanRequest* _request = nullptr;
274
};
275
276
struct FileAggregateRequest {
277
    struct Column {
278
        // File-local projection for the aggregate column. For nested MIN/MAX, this points to the
279
        // single primitive leaf that can be represented by file statistics. For COUNT(col), this
280
        // points to the top-level column whose NULL-ness should be counted.
281
        LocalColumnIndex projection;
282
    };
283
284
    TPushAggOp::type agg_type = TPushAggOp::type::NONE;
285
    // Empty for COUNT(*)/row-count pushdown. Non-empty for COUNT(col), where the file reader must
286
    // return the number of non-NULL rows for the requested column instead of total rows.
287
    std::vector<Column> columns;
288
};
289
290
struct FileAggregateResult {
291
    struct Column {
292
        // Mirrors FileAggregateRequest::Column::projection so TableReader can put the returned
293
        // aggregate value back into the matching projected nested shape.
294
        LocalColumnIndex projection;
295
        bool has_min = false;
296
        bool has_max = false;
297
        Field min_value;
298
        Field max_value;
299
    };
300
301
    int64_t count = 0;
302
    std::vector<Column> columns;
303
};
304
305
/**
306
 *                                +-----> get_schema() -----------------+
307
 * FileReader() -----> init() ----|                                      -----> close()
308
 *                                +-----> open() -----> get_block() ----+
309
 */
310
class FileReader {
311
public:
312
    struct ReaderStatistics {
313
        int32_t filtered_row_groups = 0;
314
        int32_t filtered_row_groups_by_min_max = 0;
315
        int32_t filtered_row_groups_by_bloom_filter = 0;
316
        int32_t read_row_groups = 0;
317
        int64_t filtered_group_rows = 0;
318
        int64_t filtered_page_rows = 0;
319
        int64_t lazy_read_filtered_rows = 0;
320
        int64_t read_rows = 0;
321
        int64_t filtered_bytes = 0;
322
        int64_t column_read_time = 0;
323
        int64_t parse_meta_time = 0;
324
        int64_t parse_footer_time = 0;
325
        int64_t file_footer_read_calls = 0;
326
        int64_t file_footer_hit_cache = 0;
327
        int64_t file_reader_create_time = 0;
328
        int64_t open_file_num = 0;
329
        int64_t row_group_filter_time = 0;
330
        int64_t page_index_filter_time = 0;
331
        int64_t read_page_index_time = 0;
332
        int64_t parse_page_index_time = 0;
333
        int64_t predicate_filter_time = 0;
334
        int64_t dict_filter_rewrite_time = 0;
335
        int64_t bloom_filter_read_time = 0;
336
    };
337
338
    FileReader(std::shared_ptr<io::FileSystemProperties>& system_properties,
339
               std::unique_ptr<io::FileDescription>& file_description,
340
               std::shared_ptr<io::IOContext> io_ctx, RuntimeProfile* profile)
341
698
            : _system_properties(system_properties),
342
698
              _file_description(std::move(file_description)),
343
698
              _io_ctx(io_ctx),
344
698
              _profile(profile) {}
345
698
    virtual ~FileReader() = default;
346
347
    // Initialize file reader and parse file metadata.
348
    virtual Status init(RuntimeState* state);
349
350
    // Set the maximum row count for the next physical read batch. Readers that do not batch by
351
    // rows may ignore it.
352
0
    virtual void set_batch_size(size_t batch_size) { (void)batch_size; }
353
354
    // Get semantic file-local schema from file metadata. The file schema is determined by file
355
    // format and file content, and does not contain table/global schema semantics. A file reader may
356
    // expose raw file identifiers, such as Parquet field_id, through ColumnDefinition::identifier,
357
    // but it must not interpret table-format semantics such as Iceberg name mapping,
358
    // default/generated columns, or partition columns. File-format physical wrappers should be
359
    // normalized away before exposing this schema; for example, Parquet MAP is exposed as key/value
360
    // children rather than key_value/entry.
361
    // Doris plans external-table scan types as nullable, including all nested children of complex
362
    // types. This protects Doris from illegal or inconsistent values produced by external systems.
363
    // Therefore every ColumnDefinition::type returned here must be nullable. Complex types must
364
    // also expose nullable child types recursively, even if the physical file marks those fields as
365
    // required.
366
    // This method can only be called after init() successfully, but does not require open() to be
367
    // called.
368
    virtual Status get_schema(std::vector<ColumnDefinition>* file_schema) const = 0;
369
370
    // Create the mapper that matches this reader's scan-request capabilities. TableReader still
371
    // owns table-format semantics such as BY_NAME/BY_FIELD_ID/BY_INDEX, partition values and
372
    // default expressions; the FileReader only chooses whether file-local requests support columnar
373
    // lazy materialization/pruning or must materialize one flat list of required columns.
374
    virtual std::unique_ptr<TableColumnMapper> create_column_mapper(
375
            TableColumnMapperOptions options) const;
376
377
    // Open the file reader with file-local scan request. The file reader should initialize its internal state according to the request, but does not need to interpret table/global schema semantics. For example, all schema change, filter localization, default/generated/partition columns should be handled in table reader layer. This method can only be called after init() successfully.
378
642
    virtual Status open(std::shared_ptr<FileScanRequest> request) {
379
642
        _request = std::move(request);
380
642
        return Status::OK();
381
642
    }
382
383
    // Readers opt in only when they can keep an immutable request for the active physical
384
    // granule and switch a newer snapshot at a well-defined boundary.
385
0
    virtual bool supports_scan_request_refresh() const { return false; }
386
387
0
    virtual Status queue_scan_request(std::shared_ptr<FileScanRequest> request) {
388
0
        (void)request;
389
0
        return Status::NotSupported("FileReader does not support scan request refresh");
390
0
    }
391
392
0
    virtual Status get_block(Block* file_block, size_t* rows, bool* eof) {
393
0
        if (rows != nullptr) {
394
0
            *rows = 0;
395
0
        }
396
0
        if (eof != nullptr) {
397
0
            *eof = true;
398
0
        }
399
0
        _eof = true;
400
0
        return Status::OK();
401
0
    }
402
403
    virtual Status get_aggregate_result(const FileAggregateRequest& request,
404
0
                                        FileAggregateResult* result) {
405
0
        return Status::NotSupported("FileReader does not support aggregate pushdown");
406
0
    }
407
408
    // Condition cache is managed by TableReader and consumed by physical file readers.
409
    // On cache HIT, readers may skip granules whose cached bit is false before doing column IO.
410
    // On cache MISS, readers mark a granule true when row-level predicates keep at least one row
411
    // in that granule. Readers that cannot map batch rows to stable file-global row ids should
412
    // keep the default no-op implementation.
413
0
    virtual void set_condition_cache_context(std::shared_ptr<ConditionCacheContext> ctx) {}
414
415
    // Total rows covered by this physical reader. TableReader uses it to pre-size the miss bitmap.
416
    // Readers should return 0 if the metadata is unavailable or the row coordinate is unstable.
417
0
    virtual int64_t get_total_rows() const { return 0; }
418
419
205
    virtual Status close() {
420
205
        _file_reader.reset();
421
205
        _tracing_file_reader.reset();
422
205
        _io_ctx.reset();
423
205
        _eof = true;
424
205
        return Status::OK();
425
205
    }
426
427
protected:
428
0
    virtual void _init_profile() {}
429
589
    void _record_scan_rows(int64_t rows) {
430
589
        DORIS_CHECK(rows >= 0);
431
589
        _reader_statistics.read_rows += rows;
432
589
        if (_io_ctx != nullptr && _io_ctx->file_reader_stats != nullptr) {
433
178
            _io_ctx->file_reader_stats->read_rows += cast_set<size_t>(rows);
434
178
        }
435
589
    }
436
437
    io::FileReaderSPtr _file_reader;
438
    // _tracing_file_reader wraps _file_reader.
439
    // _file_reader is original file reader.
440
    // _tracing_file_reader is tracing file reader with io context.
441
    // If io_ctx is null, _tracing_file_reader will be the same as file_reader.
442
    io::FileReaderSPtr _tracing_file_reader = nullptr;
443
    std::shared_ptr<FileScanRequest> _request;
444
    bool _eof = true;
445
    ReaderStatistics _reader_statistics;
446
    std::shared_ptr<io::FileSystemProperties> _system_properties;
447
    std::unique_ptr<io::FileDescription> _file_description;
448
    std::shared_ptr<io::IOContext> _io_ctx;
449
    RuntimeProfile* _profile = nullptr;
450
};
451
452
} // namespace doris::format