Coverage Report

Created: 2026-10-27 11:57

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