Coverage Report

Created: 2026-10-26 10:12

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