Coverage Report

Created: 2026-07-14 07:41

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