Coverage Report

Created: 2026-07-21 00:36

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 <map>
22
#include <memory>
23
#include <string>
24
#include <utility>
25
#include <vector>
26
27
#include "common/cast_set.h"
28
#include "common/status.h"
29
#include "core/data_type/data_type.h"
30
#include "core/field.h"
31
#include "exprs/vexpr_fwd.h"
32
#include "format_v2/column_data.h"
33
#include "gen_cpp/PlanNodes_types.h"
34
#include "io/file_factory.h"
35
#include "io/fs/file_reader_writer_fwd.h"
36
37
namespace doris {
38
class Block;
39
struct ConditionCacheContext;
40
41
namespace io {
42
struct IOContext;
43
} // namespace io
44
} // namespace doris
45
46
namespace doris::format {
47
48
class TableColumnMapper;
49
struct TableColumnMapperOptions;
50
51
enum class FileFormat {
52
    PARQUET,
53
    ORC,
54
    CSV,
55
    JSON,
56
    TEXT,
57
    JNI,
58
    NATIVE,
59
    ARROW,
60
};
61
62
struct FileScanRequest {
63
540
    virtual ~FileScanRequest() = default;
64
65
    std::string debug_string() const;
66
67
    // Columns that must be read before row-level filtering. They are materialized eagerly because
68
    // conjuncts/delete_conjuncts need them to decide the selected rows.
69
    std::vector<LocalColumnIndex> predicate_columns;
70
    // Columns read after row-level filtering. Predicate columns are also available for output and
71
    // should not be duplicated here.
72
    std::vector<LocalColumnIndex> non_predicate_columns;
73
    // Predicate columns introduced only to evaluate hidden filter slots. Their values are dead
74
    // after all file-local predicates run, although the shared file block still needs row-shaped
75
    // placeholders until TableReader finalizes projected columns.
76
    std::vector<LocalColumnId> predicate_only_columns;
77
    // file-local column id -> file-local output block position.
78
    std::map<LocalColumnId, LocalIndex> local_positions;
79
    // Row-level filters converted to file-local expressions from table-level predicates.
80
    VExprContextSPtrs conjuncts;
81
    // Delete predicates converted to file-local expressions. A TRUE result means that the row is
82
    // deleted, so readers must invert each result when building their keep filter.
83
    VExprContextSPtrs delete_conjuncts;
84
    // File-local ids retained only because Nereids keeps a minimum-width output tuple for an
85
    // explicit COUNT(*). These columns have no semantic value: for example, after pruning a scan
86
    // may retain an unsupported TIME_MILLIS leaf even though COUNT(*) only needs one row per
87
    // surviving input row. A reader may synthesize defaults instead of reading a marked column
88
    // while it remains non-predicate. If filters or equality deletes promote the same id to
89
    // predicate_columns, the value is semantically required and must still be validated and read.
90
    std::vector<LocalColumnId> count_star_placeholder_columns;
91
92
1.01k
    bool is_count_star_placeholder(LocalColumnId column_id) const {
93
1.01k
        return std::ranges::find(count_star_placeholder_columns, column_id) !=
94
1.01k
               count_star_placeholder_columns.end();
95
1.01k
    }
96
97
70
    bool is_predicate_only(LocalColumnId column_id) const {
98
70
        return std::ranges::find(predicate_only_columns, column_id) != predicate_only_columns.end();
99
70
    }
100
};
101
102
// Helper for constructing the scan-column layout in FileScanRequest.
103
// FileScanRequest keeps predicate and non-predicate columns separate because columnar readers such
104
// as Parquet can read predicate columns first, filter rows, and then lazily read the remaining
105
// projected columns. The two lists still share one file-local output block, whose positions are
106
// stored in local_positions. This builder centralizes the mechanical rules for that shared layout:
107
// - each root file column gets one stable block position;
108
// - predicate columns dominate non-predicate columns because they are already returned in the file
109
//   block and can be reused for final materialization;
110
// - repeated nested projections for the same root are merged instead of duplicated.
111
// TableColumnMapper should still own table-to-file semantic resolution. This helper only owns the
112
// FileScanRequest layout contract after a file-local projection has been produced.
113
class FileScanRequestBuilder {
114
public:
115
278
    explicit FileScanRequestBuilder(FileScanRequest* request) : _request(request) {
116
278
        DORIS_CHECK(_request != nullptr);
117
278
    }
118
119
138
    Status add_predicate_column(LocalColumnIndex projection) {
120
138
        return _add_column(std::move(projection), &_request->predicate_columns,
121
138
                           /*is_predicate_column=*/true);
122
138
    }
123
124
162
    Status add_non_predicate_column(LocalColumnIndex projection) {
125
162
        return _add_column(std::move(projection), &_request->non_predicate_columns,
126
162
                           /*is_predicate_column=*/false);
127
162
    }
128
129
56
    Status add_predicate_column(LocalColumnId column_id) {
130
56
        return add_predicate_column(LocalColumnIndex::top_level(column_id));
131
56
    }
132
133
37
    Status add_non_predicate_column(LocalColumnId column_id) {
134
37
        return add_non_predicate_column(LocalColumnIndex::top_level(column_id));
135
37
    }
136
137
private:
138
283
    static LocalIndex _next_block_position(const FileScanRequest& request) {
139
283
        size_t next_position = 0;
140
283
        for (const auto& [_, block_position] : request.local_positions) {
141
102
            next_position = std::max(next_position, block_position.value() + 1);
142
102
        }
143
283
        return LocalIndex(next_position);
144
283
    }
145
146
353
    static void _sort_projection_children_by_file_id(LocalColumnIndex* projection) {
147
353
        DORIS_CHECK(projection != nullptr);
148
353
        if (projection->project_all_children) {
149
318
            return;
150
318
        }
151
51
        for (auto& child : projection->children) {
152
51
            _sort_projection_children_by_file_id(&child);
153
51
        }
154
35
        std::ranges::sort(projection->children,
155
35
                          [](const LocalColumnIndex& lhs, const LocalColumnIndex& rhs) {
156
23
                              return lhs.local_id() < rhs.local_id();
157
23
                          });
158
35
    }
159
160
    Status _add_column(LocalColumnIndex projection, std::vector<LocalColumnIndex>* scan_columns,
161
300
                       bool is_predicate_column) {
162
300
        DORIS_CHECK(scan_columns != nullptr);
163
300
        const auto file_column_id = projection.column_id();
164
300
        DORIS_CHECK(file_column_id != LocalColumnId::invalid());
165
300
        if (!is_predicate_column &&
166
300
            std::ranges::find_if(_request->predicate_columns, [&](const LocalColumnIndex& p) {
167
15
                return p.column_id() == file_column_id;
168
15
            }) != _request->predicate_columns.end()) {
169
2
            return Status::OK();
170
2
        }
171
298
        if (!_request->local_positions.contains(file_column_id)) {
172
283
            _request->local_positions.emplace(file_column_id, _next_block_position(*_request));
173
283
        }
174
175
298
        _sort_projection_children_by_file_id(&projection);
176
298
        auto existing_projection_it = std::ranges::find_if(
177
298
                *scan_columns,
178
298
                [&](const LocalColumnIndex& p) { return p.column_id() == file_column_id; });
179
298
        if (existing_projection_it == scan_columns->end()) {
180
294
            scan_columns->push_back(std::move(projection));
181
294
        } else {
182
4
            RETURN_IF_ERROR(merge_local_column_index(&*existing_projection_it, projection));
183
4
            _sort_projection_children_by_file_id(&*existing_projection_it);
184
4
        }
185
186
298
        if (is_predicate_column) {
187
138
            auto it = std::ranges::find_if(
188
138
                    _request->non_predicate_columns,
189
138
                    [&](const LocalColumnIndex& p) { return p.column_id() == file_column_id; });
190
138
            if (it != _request->non_predicate_columns.end()) {
191
10
                _request->non_predicate_columns.erase(it);
192
10
            }
193
138
        }
194
298
        return Status::OK();
195
298
    }
196
197
    FileScanRequest* _request = nullptr;
198
};
199
200
struct FileAggregateRequest {
201
    struct Column {
202
        // File-local projection for the aggregate column. For nested MIN/MAX, this points to the
203
        // single primitive leaf that can be represented by file statistics. For COUNT(col), this
204
        // points to the top-level column whose NULL-ness should be counted.
205
        LocalColumnIndex projection;
206
    };
207
208
    TPushAggOp::type agg_type = TPushAggOp::type::NONE;
209
    // Empty for COUNT(*)/row-count pushdown. Non-empty for COUNT(col), where the file reader must
210
    // return the number of non-NULL rows for the requested column instead of total rows.
211
    std::vector<Column> columns;
212
};
213
214
struct FileAggregateResult {
215
    struct Column {
216
        // Mirrors FileAggregateRequest::Column::projection so TableReader can put the returned
217
        // aggregate value back into the matching projected nested shape.
218
        LocalColumnIndex projection;
219
        bool has_min = false;
220
        bool has_max = false;
221
        Field min_value;
222
        Field max_value;
223
    };
224
225
    int64_t count = 0;
226
    std::vector<Column> columns;
227
};
228
229
/**
230
 *                                +-----> get_schema() -----------------+
231
 * FileReader() -----> init() ----|                                      -----> close()
232
 *                                +-----> open() -----> get_block() ----+
233
 */
234
class FileReader {
235
public:
236
    struct ReaderStatistics {
237
        int32_t filtered_row_groups = 0;
238
        int32_t filtered_row_groups_by_min_max = 0;
239
        int32_t filtered_row_groups_by_bloom_filter = 0;
240
        int32_t read_row_groups = 0;
241
        int64_t filtered_group_rows = 0;
242
        int64_t filtered_page_rows = 0;
243
        int64_t lazy_read_filtered_rows = 0;
244
        int64_t read_rows = 0;
245
        int64_t filtered_bytes = 0;
246
        int64_t column_read_time = 0;
247
        int64_t parse_meta_time = 0;
248
        int64_t parse_footer_time = 0;
249
        int64_t file_footer_read_calls = 0;
250
        int64_t file_footer_hit_cache = 0;
251
        int64_t file_reader_create_time = 0;
252
        int64_t open_file_num = 0;
253
        int64_t row_group_filter_time = 0;
254
        int64_t page_index_filter_time = 0;
255
        int64_t read_page_index_time = 0;
256
        int64_t parse_page_index_time = 0;
257
        int64_t predicate_filter_time = 0;
258
        int64_t dict_filter_rewrite_time = 0;
259
        int64_t bloom_filter_read_time = 0;
260
    };
261
262
    FileReader(std::shared_ptr<io::FileSystemProperties>& system_properties,
263
               std::unique_ptr<io::FileDescription>& file_description,
264
               std::shared_ptr<io::IOContext> io_ctx, RuntimeProfile* profile)
265
500
            : _system_properties(system_properties),
266
500
              _file_description(std::move(file_description)),
267
500
              _io_ctx(io_ctx),
268
500
              _profile(profile) {}
269
500
    virtual ~FileReader() = default;
270
271
    // Initialize file reader and parse file metadata.
272
    virtual Status init(RuntimeState* state);
273
274
    // Set the maximum row count for the next physical read batch. Readers that do not batch by
275
    // rows may ignore it.
276
0
    virtual void set_batch_size(size_t batch_size) { (void)batch_size; }
277
278
    // Get semantic file-local schema from file metadata. The file schema is determined by file
279
    // format and file content, and does not contain table/global schema semantics. A file reader may
280
    // expose raw file identifiers, such as Parquet field_id, through ColumnDefinition::identifier,
281
    // but it must not interpret table-format semantics such as Iceberg name mapping,
282
    // default/generated columns, or partition columns. File-format physical wrappers should be
283
    // normalized away before exposing this schema; for example, Parquet MAP is exposed as key/value
284
    // children rather than key_value/entry.
285
    // Doris plans external-table scan types as nullable, including all nested children of complex
286
    // types. This protects Doris from illegal or inconsistent values produced by external systems.
287
    // Therefore every ColumnDefinition::type returned here must be nullable. Complex types must
288
    // also expose nullable child types recursively, even if the physical file marks those fields as
289
    // required.
290
    // This method can only be called after init() successfully, but does not require open() to be
291
    // called.
292
    virtual Status get_schema(std::vector<ColumnDefinition>* file_schema) const = 0;
293
294
    // Create the mapper that matches this reader's scan-request capabilities. TableReader still
295
    // owns table-format semantics such as BY_NAME/BY_FIELD_ID/BY_INDEX, partition values and
296
    // default expressions; the FileReader only chooses whether file-local requests support columnar
297
    // lazy materialization/pruning or must materialize one flat list of required columns.
298
    virtual std::unique_ptr<TableColumnMapper> create_column_mapper(
299
            TableColumnMapperOptions options) const;
300
301
    // 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.
302
454
    virtual Status open(std::shared_ptr<FileScanRequest> request) {
303
454
        _request = std::move(request);
304
454
        return Status::OK();
305
454
    }
306
307
0
    virtual Status get_block(Block* file_block, size_t* rows, bool* eof) {
308
0
        if (rows != nullptr) {
309
0
            *rows = 0;
310
0
        }
311
0
        if (eof != nullptr) {
312
0
            *eof = true;
313
0
        }
314
0
        _eof = true;
315
0
        return Status::OK();
316
0
    }
317
318
    virtual Status get_aggregate_result(const FileAggregateRequest& request,
319
0
                                        FileAggregateResult* result) {
320
0
        return Status::NotSupported("FileReader does not support aggregate pushdown");
321
0
    }
322
323
    // Condition cache is managed by TableReader and consumed by physical file readers.
324
    // On cache HIT, readers may skip granules whose cached bit is false before doing column IO.
325
    // On cache MISS, readers mark a granule true when row-level predicates keep at least one row
326
    // in that granule. Readers that cannot map batch rows to stable file-global row ids should
327
    // keep the default no-op implementation.
328
0
    virtual void set_condition_cache_context(std::shared_ptr<ConditionCacheContext> ctx) {}
329
330
    // Total rows covered by this physical reader. TableReader uses it to pre-size the miss bitmap.
331
    // Readers should return 0 if the metadata is unavailable or the row coordinate is unstable.
332
0
    virtual int64_t get_total_rows() const { return 0; }
333
334
125
    virtual Status close() {
335
125
        _file_reader.reset();
336
125
        _tracing_file_reader.reset();
337
125
        _io_ctx.reset();
338
125
        _eof = true;
339
125
        return Status::OK();
340
125
    }
341
342
protected:
343
0
    virtual void _init_profile() {}
344
344
    void _record_scan_rows(int64_t rows) {
345
344
        DORIS_CHECK(rows >= 0);
346
344
        _reader_statistics.read_rows += rows;
347
344
        if (_io_ctx != nullptr && _io_ctx->file_reader_stats != nullptr) {
348
112
            _io_ctx->file_reader_stats->read_rows += cast_set<size_t>(rows);
349
112
        }
350
344
    }
351
352
    io::FileReaderSPtr _file_reader;
353
    // _tracing_file_reader wraps _file_reader.
354
    // _file_reader is original file reader.
355
    // _tracing_file_reader is tracing file reader with io context.
356
    // If io_ctx is null, _tracing_file_reader will be the same as file_reader.
357
    io::FileReaderSPtr _tracing_file_reader = nullptr;
358
    std::shared_ptr<FileScanRequest> _request;
359
    bool _eof = true;
360
    ReaderStatistics _reader_statistics;
361
    std::shared_ptr<io::FileSystemProperties> _system_properties;
362
    std::unique_ptr<io::FileDescription> _file_description;
363
    std::shared_ptr<io::IOContext> _io_ctx;
364
    RuntimeProfile* _profile = nullptr;
365
};
366
367
} // namespace doris::format