Coverage Report

Created: 2026-07-07 19:59

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