Coverage Report

Created: 2026-10-27 02:53

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