Coverage Report

Created: 2026-07-24 23:23

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