Coverage Report

Created: 2026-09-18 20:49

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 <functional>
22
#include <limits>
23
#include <map>
24
#include <memory>
25
#include <string>
26
#include <utility>
27
#include <vector>
28
29
#include "common/cast_set.h"
30
#include "common/status.h"
31
#include "core/data_type/data_type.h"
32
#include "core/field.h"
33
#include "exprs/vexpr_fwd.h"
34
#include "format_v2/column_data.h"
35
#include "gen_cpp/PlanNodes_types.h"
36
#include "io/file_factory.h"
37
#include "io/fs/file_reader_writer_fwd.h"
38
#include "io/io_common.h"
39
40
namespace doris {
41
class Block;
42
struct ConditionCacheContext;
43
44
namespace io {
45
struct IOContext;
46
} // namespace io
47
} // namespace doris
48
49
namespace doris::format {
50
51
class TableColumnMapper;
52
struct TableColumnMapperOptions;
53
54
enum class FileFormat {
55
    PARQUET,
56
    ORC,
57
    CSV,
58
    JSON,
59
    TEXT,
60
    JNI,
61
    ARROW,
62
    WAL,
63
};
64
65
struct FileScanRequest {
66
891
    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
    // Absolute zero-based file row positions selected by a row-id fetch. A present but empty
106
    // vector means that no rows should be read; nullopt keeps the normal sequential scan path.
107
    // Readers require strictly increasing positions so they can seek forward without duplicating
108
    // output rows.
109
    std::optional<std::vector<int64_t>> row_ids = std::nullopt;
110
111
    // Table formats may assign semantics that legacy physical files do not encode. Each path here
112
    // identifies an unannotated Parquet group that the physical reader must validate and decode as
113
    // Variant. Keeping this explicit prevents generic Parquet scans from guessing based on names.
114
    std::vector<LocalColumnIndex> variant_schema_overrides;
115
116
2.44k
    bool is_count_star_placeholder(LocalColumnId column_id) const {
117
2.44k
        return std::ranges::find(count_star_placeholder_columns, column_id) !=
118
2.44k
               count_star_placeholder_columns.end();
119
2.44k
    }
120
121
214
    bool is_predicate_only(LocalColumnId column_id) const {
122
214
        return std::ranges::find(predicate_only_columns, column_id) != predicate_only_columns.end();
123
214
    }
124
125
1.15k
    LocalIndex non_predicate_position(LocalColumnId column_id) const {
126
1.15k
        const auto it = non_predicate_positions.find(column_id);
127
1.15k
        return it == non_predicate_positions.end() ? local_positions.at(column_id) : it->second;
128
1.15k
    }
129
130
1.03k
    bool has_deferred_non_predicate_column(LocalColumnId column_id) const {
131
1.03k
        return non_predicate_positions.contains(column_id);
132
1.03k
    }
133
134
166
    size_t block_column_count() const {
135
166
        size_t count = 0;
136
245
        for (const auto& [_, position] : local_positions) {
137
245
            count = std::max(count, position.value() + 1);
138
245
        }
139
166
        for (const auto& [_, position] : non_predicate_positions) {
140
0
            count = std::max(count, position.value() + 1);
141
0
        }
142
166
        return count;
143
166
    }
144
};
145
146
// Helper for constructing the scan-column layout in FileScanRequest.
147
// FileScanRequest keeps predicate and non-predicate columns separate because columnar readers such
148
// as Parquet can read predicate columns first, filter rows, and then lazily read the remaining
149
// projected columns. The two lists still share one file-local output block, whose positions are
150
// stored in local_positions. This builder centralizes the mechanical rules for that shared layout:
151
// - each root file column gets one stable predicate block position;
152
// - predicate columns dominate non-predicate columns because they are already returned in the file
153
//   block and can be reused for final materialization;
154
// - a smaller complex predicate subtree may get a second deferred output position;
155
// - repeated nested projections for the same root are merged instead of duplicated.
156
// TableColumnMapper should still own table-to-file semantic resolution. This helper only owns the
157
// FileScanRequest layout contract after a file-local projection has been produced.
158
class FileScanRequestBuilder {
159
public:
160
552
    explicit FileScanRequestBuilder(FileScanRequest* request) : _request(request) {
161
552
        DORIS_CHECK(_request != nullptr);
162
552
    }
163
164
264
    Status add_predicate_column(LocalColumnIndex projection) {
165
264
        return _add_column(std::move(projection), &_request->predicate_columns,
166
264
                           /*is_predicate_column=*/true);
167
264
    }
168
169
500
    Status add_non_predicate_column(LocalColumnIndex projection) {
170
500
        return _add_column(std::move(projection), &_request->non_predicate_columns,
171
500
                           /*is_predicate_column=*/false);
172
500
    }
173
174
11
    Status add_deferred_non_predicate_column(LocalColumnIndex projection) {
175
11
        const auto file_column_id = projection.column_id();
176
11
        DORIS_CHECK(file_column_id != LocalColumnId::invalid());
177
11
        DORIS_CHECK(_request->local_positions.contains(file_column_id));
178
11
        DORIS_CHECK(std::ranges::any_of(_request->predicate_columns,
179
11
                                        [&](const LocalColumnIndex& predicate) {
180
11
                                            return predicate.column_id() == file_column_id;
181
11
                                        }));
182
183
11
        if (!_request->non_predicate_positions.contains(file_column_id)) {
184
9
            _request->non_predicate_positions.emplace(file_column_id,
185
9
                                                      _next_block_position(*_request));
186
9
        }
187
11
        _sort_projection_children_by_file_id(&projection);
188
11
        auto existing = std::ranges::find_if(_request->non_predicate_columns,
189
11
                                             [&](const LocalColumnIndex& output) {
190
2
                                                 return output.column_id() == file_column_id;
191
2
                                             });
192
11
        if (existing == _request->non_predicate_columns.end()) {
193
11
            _request->non_predicate_columns.push_back(std::move(projection));
194
11
        } else {
195
0
            RETURN_IF_ERROR(merge_local_column_index(&*existing, projection));
196
0
            _sort_projection_children_by_file_id(&*existing);
197
0
        }
198
11
        if (!_request->is_predicate_only(file_column_id)) {
199
            // The eager complex value has a different physical shape from the final value and
200
            // must never leak into table materialization after its predicates have run.
201
11
            _request->predicate_only_columns.push_back(file_column_id);
202
11
        }
203
11
        return Status::OK();
204
11
    }
205
206
160
    Status add_predicate_column(LocalColumnId column_id) {
207
160
        return add_predicate_column(LocalColumnIndex::top_level(column_id));
208
160
    }
209
210
290
    Status add_non_predicate_column(LocalColumnId column_id) {
211
290
        return add_non_predicate_column(LocalColumnIndex::top_level(column_id));
212
290
    }
213
214
private:
215
710
    static LocalIndex _next_block_position(const FileScanRequest& request) {
216
710
        size_t next_position = 0;
217
8.36k
        for (const auto& [_, block_position] : request.local_positions) {
218
8.36k
            next_position = std::max(next_position, block_position.value() + 1);
219
8.36k
        }
220
710
        for (const auto& [_, block_position] : request.non_predicate_positions) {
221
3
            next_position = std::max(next_position, block_position.value() + 1);
222
3
        }
223
710
        return LocalIndex(next_position);
224
710
    }
225
226
886
    static void _sort_projection_children_by_file_id(LocalColumnIndex* projection) {
227
886
        DORIS_CHECK(projection != nullptr);
228
886
        if (projection->project_all_children) {
229
796
            return;
230
796
        }
231
107
        for (auto& child : projection->children) {
232
107
            _sort_projection_children_by_file_id(&child);
233
107
        }
234
90
        std::ranges::sort(projection->children,
235
90
                          [](const LocalColumnIndex& lhs, const LocalColumnIndex& rhs) {
236
32
                              return lhs.local_id() < rhs.local_id();
237
32
                          });
238
90
    }
239
240
    Status _add_column(LocalColumnIndex projection, std::vector<LocalColumnIndex>* scan_columns,
241
764
                       bool is_predicate_column) {
242
764
        DORIS_CHECK(scan_columns != nullptr);
243
764
        const auto file_column_id = projection.column_id();
244
764
        DORIS_CHECK(file_column_id != LocalColumnId::invalid());
245
764
        if (!is_predicate_column &&
246
764
            std::ranges::find_if(_request->predicate_columns,
247
500
                                 [&](const LocalColumnIndex& p) {
248
76
                                     return p.column_id() == file_column_id;
249
76
                                 }) != _request->predicate_columns.end() &&
250
764
            !_request->has_deferred_non_predicate_column(file_column_id)) {
251
2
            return Status::OK();
252
2
        }
253
762
        if (!_request->local_positions.contains(file_column_id)) {
254
701
            _request->local_positions.emplace(file_column_id, _next_block_position(*_request));
255
701
        }
256
257
762
        _sort_projection_children_by_file_id(&projection);
258
762
        auto existing_projection_it = std::ranges::find_if(
259
762
                *scan_columns,
260
8.09k
                [&](const LocalColumnIndex& p) { return p.column_id() == file_column_id; });
261
762
        if (existing_projection_it == scan_columns->end()) {
262
756
            scan_columns->push_back(std::move(projection));
263
756
        } else {
264
6
            RETURN_IF_ERROR(merge_local_column_index(&*existing_projection_it, projection));
265
6
            _sort_projection_children_by_file_id(&*existing_projection_it);
266
6
        }
267
268
762
        if (is_predicate_column && !_request->has_deferred_non_predicate_column(file_column_id)) {
269
261
            auto it = std::ranges::find_if(
270
261
                    _request->non_predicate_columns,
271
261
                    [&](const LocalColumnIndex& p) { return p.column_id() == file_column_id; });
272
261
            if (it != _request->non_predicate_columns.end()) {
273
13
                _request->non_predicate_columns.erase(it);
274
13
            }
275
261
        }
276
762
        return Status::OK();
277
762
    }
278
279
    FileScanRequest* _request = nullptr;
280
};
281
282
struct FileAggregateRequest {
283
    struct Column {
284
        // File-local projection for the aggregate column. For nested MIN/MAX, this points to the
285
        // single primitive leaf that can be represented by file statistics. For COUNT(col), this
286
        // points to the top-level column whose NULL-ness should be counted.
287
        LocalColumnIndex projection;
288
    };
289
290
    TPushAggOp::type agg_type = TPushAggOp::type::NONE;
291
    // Empty for COUNT(*)/row-count pushdown. Non-empty for COUNT(col), where the file reader must
292
    // return the number of non-NULL rows for the requested column instead of total rows.
293
    std::vector<Column> columns;
294
};
295
296
struct FileAggregateResult {
297
    struct Column {
298
        // Mirrors FileAggregateRequest::Column::projection so TableReader can put the returned
299
        // aggregate value back into the matching projected nested shape.
300
        LocalColumnIndex projection;
301
        bool has_min = false;
302
        bool has_max = false;
303
        Field min_value;
304
        Field max_value;
305
    };
306
307
    int64_t count = 0;
308
    std::vector<Column> columns;
309
};
310
311
/**
312
 *                                +-----> get_schema() -----------------+
313
 * FileReader() -----> init() ----|                                      -----> close()
314
 *                                +-----> open() -----> get_block() ----+
315
 */
316
class FileReader {
317
public:
318
    struct ReaderStatistics {
319
        int32_t filtered_row_groups = 0;
320
        int32_t filtered_row_groups_by_min_max = 0;
321
        int32_t filtered_row_groups_by_bloom_filter = 0;
322
        int32_t read_row_groups = 0;
323
        int64_t filtered_group_rows = 0;
324
        int64_t filtered_page_rows = 0;
325
        int64_t lazy_read_filtered_rows = 0;
326
        int64_t read_rows = 0;
327
        int64_t filtered_bytes = 0;
328
        int64_t column_read_time = 0;
329
        int64_t parse_meta_time = 0;
330
        int64_t parse_footer_time = 0;
331
        int64_t file_footer_read_calls = 0;
332
        int64_t file_footer_hit_cache = 0;
333
        int64_t file_reader_create_time = 0;
334
        int64_t open_file_num = 0;
335
        int64_t row_group_filter_time = 0;
336
        int64_t page_index_filter_time = 0;
337
        int64_t read_page_index_time = 0;
338
        int64_t parse_page_index_time = 0;
339
        int64_t predicate_filter_time = 0;
340
        int64_t dict_filter_rewrite_time = 0;
341
        int64_t bloom_filter_read_time = 0;
342
    };
343
344
    FileReader(std::shared_ptr<io::FileSystemProperties>& system_properties,
345
               std::unique_ptr<io::FileDescription>& file_description,
346
               std::shared_ptr<io::IOContext> io_ctx, RuntimeProfile* profile)
347
769
            : _system_properties(system_properties),
348
769
              _file_description(std::move(file_description)),
349
769
              _io_ctx(io_ctx),
350
769
              _profile(profile) {}
351
769
    virtual ~FileReader() = default;
352
353
    // Initialize file reader and parse file metadata.
354
    virtual Status init(RuntimeState* state);
355
356
    // Set the maximum row count for the next physical read batch. Readers that do not batch by
357
    // rows may ignore it.
358
0
    virtual void set_batch_size(size_t batch_size) { (void)batch_size; }
359
360
    // Get semantic file-local schema from file metadata. The file schema is determined by file
361
    // format and file content, and does not contain table/global schema semantics. A file reader may
362
    // expose raw file identifiers, such as Parquet field_id, through ColumnDefinition::identifier,
363
    // but it must not interpret table-format semantics such as Iceberg name mapping,
364
    // default/generated columns, or partition columns. File-format physical wrappers should be
365
    // normalized away before exposing this schema; for example, Parquet MAP is exposed as key/value
366
    // children rather than key_value/entry.
367
    // Doris plans external-table scan types as nullable, including all nested children of complex
368
    // types. This protects Doris from illegal or inconsistent values produced by external systems.
369
    // Therefore every ColumnDefinition::type returned here must be nullable. Complex types must
370
    // also expose nullable child types recursively, even if the physical file marks those fields as
371
    // required.
372
    // This method can only be called after init() successfully, but does not require open() to be
373
    // called.
374
    virtual Status get_schema(std::vector<ColumnDefinition>* file_schema) const = 0;
375
376
    // Create the mapper that matches this reader's scan-request capabilities. TableReader still
377
    // owns table-format semantics such as BY_NAME/BY_FIELD_ID/BY_INDEX, partition values and
378
    // default expressions; the FileReader only chooses whether file-local requests support columnar
379
    // lazy materialization/pruning or must materialize one flat list of required columns.
380
    virtual std::unique_ptr<TableColumnMapper> create_column_mapper(
381
            TableColumnMapperOptions options) const;
382
383
0
    virtual bool supports_rowid_fetch() const { return false; }
384
385
    // 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.
386
723
    virtual Status open(std::shared_ptr<FileScanRequest> request) {
387
723
        if (request->row_ids.has_value()) {
388
2
            if (!supports_rowid_fetch()) {
389
0
                return Status::NotSupported("File reader does not support row-id fetch");
390
0
            }
391
2
            const auto& row_ids = *request->row_ids;
392
6
            if (std::ranges::any_of(row_ids, [](int64_t row_id) { return row_id < 0; }) ||
393
2
                std::ranges::adjacent_find(row_ids, std::greater_equal<>()) != row_ids.end()) {
394
0
                return Status::InvalidArgument(
395
0
                        "Row-id fetch requires non-negative, strictly increasing file row ids");
396
0
            }
397
2
        }
398
723
        _request = std::move(request);
399
723
        return Status::OK();
400
723
    }
401
402
    // Readers opt in only when they can keep an immutable request for the active physical
403
    // granule and switch a newer snapshot at a well-defined boundary.
404
0
    virtual bool supports_scan_request_refresh() const { return false; }
405
406
0
    virtual Status queue_scan_request(std::shared_ptr<FileScanRequest> request) {
407
0
        (void)request;
408
0
        return Status::NotSupported("FileReader does not support scan request refresh");
409
0
    }
410
411
0
    virtual Status get_block(Block* file_block, size_t* rows, bool* eof) {
412
0
        if (rows != nullptr) {
413
0
            *rows = 0;
414
0
        }
415
0
        if (eof != nullptr) {
416
0
            *eof = true;
417
0
        }
418
0
        _eof = true;
419
0
        return Status::OK();
420
0
    }
421
422
    virtual Status get_aggregate_result(const FileAggregateRequest& request,
423
0
                                        FileAggregateResult* result) {
424
0
        return Status::NotSupported("FileReader does not support aggregate pushdown");
425
0
    }
426
427
    // Condition cache is managed by TableReader and consumed by physical file readers.
428
    // On cache HIT, readers may skip granules whose cached bit is false before doing column IO.
429
    // On cache MISS, readers mark a granule true when row-level predicates keep at least one row
430
    // in that granule. Readers that cannot map batch rows to stable file-global row ids should
431
    // keep the default no-op implementation.
432
0
    virtual void set_condition_cache_context(std::shared_ptr<ConditionCacheContext> ctx) {}
433
434
    // Total rows covered by this physical reader. TableReader uses it to pre-size the miss bitmap.
435
    // Readers should return 0 if the metadata is unavailable or the row coordinate is unstable.
436
0
    virtual int64_t get_total_rows() const { return 0; }
437
438
218
    virtual Status close() {
439
218
        _file_reader.reset();
440
218
        _tracing_file_reader.reset();
441
218
        _io_ctx.reset();
442
218
        _eof = true;
443
218
        return Status::OK();
444
218
    }
445
446
protected:
447
0
    virtual void _init_profile() {}
448
706
    void _record_scan_rows(int64_t rows) {
449
706
        DORIS_CHECK(rows >= 0);
450
706
        _reader_statistics.read_rows += rows;
451
706
        if (_io_ctx != nullptr && _io_ctx->file_reader_stats != nullptr) {
452
188
            _io_ctx->file_reader_stats->read_rows += cast_set<size_t>(rows);
453
188
        }
454
706
    }
455
456
    io::FileReaderSPtr _file_reader;
457
    // _tracing_file_reader wraps _file_reader.
458
    // _file_reader is original file reader.
459
    // _tracing_file_reader is tracing file reader with io context.
460
    // If io_ctx is null, _tracing_file_reader will be the same as file_reader.
461
    io::FileReaderSPtr _tracing_file_reader = nullptr;
462
    std::shared_ptr<FileScanRequest> _request;
463
    bool _eof = true;
464
    ReaderStatistics _reader_statistics;
465
    std::shared_ptr<io::FileSystemProperties> _system_properties;
466
    std::unique_ptr<io::FileDescription> _file_description;
467
    std::shared_ptr<io::IOContext> _io_ctx;
468
    RuntimeProfile* _profile = nullptr;
469
};
470
471
} // namespace doris::format