Coverage Report

Created: 2026-07-23 12:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format_v2/parquet/parquet_scan.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 <gen_cpp/parquet_types.h>
19
20
#include <cstddef>
21
#include <cstdint>
22
#include <map>
23
#include <memory>
24
#include <optional>
25
#include <unordered_map>
26
#include <utility>
27
#include <vector>
28
29
#include "common/status.h"
30
#include "core/column/column.h"
31
#include "format_v2/file_reader.h"
32
#include "format_v2/parquet/parquet_profile.h"
33
#include "format_v2/parquet/parquet_statistics.h"
34
#include "format_v2/parquet/reader/column_reader.h"
35
#include "format_v2/parquet/selection_vector.h"
36
#include "runtime/runtime_profile.h"
37
#include "storage/segment/condition_cache.h"
38
39
namespace cctz {
40
class time_zone;
41
} // namespace cctz
42
43
namespace doris {
44
class Block;
45
class RuntimeState;
46
47
namespace format {
48
struct FileScanRequest;
49
} // namespace format
50
} // namespace doris
51
52
namespace doris::format::parquet {
53
54
struct ParquetFileContext;
55
struct ParquetColumnSchema;
56
struct ParquetPageCacheRange;
57
struct ParquetScanRange;
58
class NativeParquetMetadata;
59
60
namespace detail {
61
struct PredicateConjunctSchedule {
62
    std::map<size_t, VExprContextSPtrs> single_column_conjuncts;
63
    VExprContextSPtrs remaining_conjuncts;
64
};
65
66
struct AdaptivePredicateStats {
67
    double cost_per_input_row_ns = 0;
68
    double survival_ratio = 1;
69
    size_t samples = 0;
70
};
71
72
std::vector<size_t> order_adaptive_predicates(
73
        const std::vector<size_t>& positions,
74
        const std::unordered_map<size_t, AdaptivePredicateStats>& stats);
75
std::vector<size_t> adaptive_prefetch_prefix(
76
        const std::vector<size_t>& ordered_positions,
77
        const std::unordered_map<size_t, AdaptivePredicateStats>& stats,
78
        double minimum_reach_probability);
79
bool should_sample_adaptive_predicate(size_t samples, size_t batch_sequence);
80
Status build_native_prefetch_ranges(
81
        const tparquet::FileMetaData& metadata,
82
        const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
83
        const std::vector<format::LocalColumnIndex>& scan_columns, int row_group_idx,
84
        size_t file_size, bool parquet_816_padding, std::vector<ParquetPageCacheRange>* ranges);
85
Status select_native_row_groups_by_scan_range(const tparquet::FileMetaData& metadata,
86
                                              const ParquetScanRange& scan_range,
87
                                              std::vector<int64_t>* row_group_first_rows,
88
                                              std::vector<int>* selected_row_groups);
89
} // namespace detail
90
91
// ============================================================================
92
// ============================================================================
93
94
struct ParquetScanRange {
95
    int64_t start_offset = 0;
96
    int64_t size = -1;      // -1 means read the whole file
97
    int64_t file_size = -1; // -1 means unknown
98
};
99
100
struct RowGroupReadPlan {
101
    int row_group_id = -1;                 // row group id
102
    int64_t first_file_row = 0;            // first file row for this row group (0-based)
103
    int64_t row_group_rows = 0;            // row count of this row group
104
    std::vector<RowRange> selected_ranges; // row ranges to read after page-index pruning
105
    std::map<int, ParquetPageSkipPlan>
106
            page_skip_plans; // leaf_column_id -> data pages that can be skipped completely
107
    // Deferred planning transfers parsed indexes to execution so narrowed scans never issue the
108
    // same remote index reads a second time while opening the row group.
109
    std::unordered_map<int, tparquet::OffsetIndex> offset_indexes;
110
    // Footer statistics are cheap and eager. Remote dictionary/Bloom/page-index probes fill the
111
    // remaining fields only when this row group reaches the scheduler.
112
    bool expensive_pruning_pending = false;
113
};
114
115
struct RowGroupScanPlan {
116
    std::vector<RowGroupReadPlan> row_groups; // row groups selected after pruning
117
    ParquetPruningStats pruning_stats;        // pruning statistics
118
    bool enable_bloom_filter = false;
119
};
120
121
// ============================================================================
122
// ============================================================================
123
124
Status plan_parquet_row_groups(const NativeParquetMetadata& metadata,
125
                               const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
126
                               const format::FileScanRequest& request,
127
                               const ParquetScanRange& scan_range, bool enable_bloom_filter,
128
                               RowGroupScanPlan* plan, const cctz::time_zone* timezone = nullptr,
129
                               const RuntimeState* runtime_state = nullptr,
130
                               ParquetFileContext* file_context = nullptr,
131
                               const ParquetColumnReaderProfile& column_reader_profile = {});
132
133
Status finalize_parquet_row_group_plans(
134
        const NativeParquetMetadata& metadata,
135
        const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
136
        const format::FileScanRequest& request, bool enable_bloom_filter, RowGroupScanPlan* plan,
137
        const cctz::time_zone* timezone, const RuntimeState* runtime_state,
138
        ParquetFileContext* file_context, const ParquetColumnReaderProfile& column_reader_profile,
139
        const ParquetProfile* parquet_profile = nullptr);
140
141
IColumn::Filter selection_to_filter(const SelectionVector& selection, uint16_t selected_rows,
142
                                    int64_t batch_rows);
143
144
uint16_t apply_compact_filter_to_selection(const IColumn::Filter& filter,
145
                                           SelectionVector* selection, uint16_t selected_rows);
146
147
Status execute_batch_filters(const format::FileScanRequest& request, int64_t batch_rows,
148
                             Block* file_block, SelectionVector* selection, uint16_t* selected_rows,
149
                             int64_t* conjunct_filtered_rows = nullptr);
150
151
// ============================================================================
152
// ============================================================================
153
//   while true:
154
//     3. read_current_row_group_batch(batch_rows)
155
// ============================================================================
156
class ParquetScanScheduler {
157
public:
158
    static constexpr int64_t DEFAULT_READ_BATCH_SIZE = 4096;
159
160
    void set_plan(RowGroupScanPlan plan);
161
210
    void set_page_skip_profile(ParquetPageSkipProfile page_skip_profile) {
162
210
        _page_skip_profile = page_skip_profile;
163
210
    }
164
210
    void set_scan_profile(ParquetScanProfile scan_profile) { _scan_profile = scan_profile; }
165
114
    void set_pruning_profile(const ParquetProfile* parquet_profile) {
166
114
        _parquet_profile = parquet_profile;
167
114
    }
168
220
    void set_merge_read_options(RuntimeProfile* profile, int64_t merge_read_slice_size) {
169
220
        _profile = profile;
170
220
        _merge_read_slice_size = merge_read_slice_size;
171
220
    }
172
210
    void set_global_rowid_context(std::optional<format::GlobalRowIdContext> context) {
173
210
        _global_rowid_context = context;
174
210
    }
175
    void set_condition_cache_context(std::shared_ptr<ConditionCacheContext> ctx);
176
220
    void set_timezone(const cctz::time_zone* timezone) { _timezone = timezone; }
177
220
    void set_enable_strict_mode(bool enable_strict_mode) {
178
220
        _enable_strict_mode = enable_strict_mode;
179
220
    }
180
220
    void set_runtime_state(RuntimeState* runtime_state) { _runtime_state = runtime_state; }
181
    // Release row-group readers before the owning RuntimeProfile is reported. Native readers
182
    // publish their accumulated page/decode statistics from their destructor.
183
121
    void close() { reset_current_row_group(); }
184
    // Upper scanner owns adaptive memory feedback; scheduler only applies the current row cap when
185
    // splitting selected row ranges into physical read batches.
186
225
    void set_batch_size(size_t batch_size) {
187
225
        _batch_size = batch_size == 0 ? 1 : static_cast<int64_t>(batch_size);
188
225
    }
189
    void reset();
190
211
    bool empty() const { return _row_group_plans.empty(); }
191
2
    int64_t condition_cache_filtered_rows() const { return _condition_cache_filtered_rows; }
192
429
    int64_t predicate_filtered_rows() const { return _predicate_filtered_rows; }
193
615
    int64_t raw_rows_read() const { return _raw_rows_read; }
194
195
    Status read_next_batch(ParquetFileContext& file_context,
196
                           const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
197
                           const format::FileScanRequest& request, Block* file_block, size_t* rows,
198
                           bool* eof);
199
200
private:
201
    static constexpr size_t PROFILE_FLUSH_BATCH_INTERVAL = 16;
202
203
    void reset_current_row_group();
204
    void flush_current_reader_profiles();
205
    bool finish_current_reader_batch_profiles();
206
    const detail::PredicateConjunctSchedule& predicate_conjunct_schedule(
207
            const format::FileScanRequest& request);
208
    std::vector<format::LocalColumnIndex> adaptive_predicate_prefetch_columns(
209
            const format::FileScanRequest& request) const;
210
211
    Status open_next_row_group(ParquetFileContext& file_context,
212
                               const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
213
                               const format::FileScanRequest& request, bool* has_row_group);
214
215
    Status skip_current_row_group_rows(int64_t rows);
216
    Status flush_pending_non_predicate_skip_rows();
217
218
    Status read_filter_columns(int64_t batch_rows, const format::FileScanRequest& request,
219
                               Block* file_block, SelectionVector* selection,
220
                               uint16_t* selected_rows, int64_t* conjunct_filtered_rows,
221
                               bool* predicate_columns_filtered);
222
223
    Status prepare_current_dictionary_filters(
224
            ParquetFileContext& file_context,
225
            const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
226
            const format::FileScanRequest& request, int row_group_idx,
227
            const tparquet::RowGroup& row_group_metadata);
228
229
    Status prefetch_current_row_group_columns(
230
            ParquetFileContext& file_context,
231
            const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
232
            const std::vector<format::LocalColumnIndex>& scan_columns, bool* prefetched);
233
234
    Status read_current_row_group_batch(
235
            ParquetFileContext& file_context,
236
            const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
237
            int64_t batch_rows, const format::FileScanRequest& request,
238
            int64_t batch_first_file_row, Block* file_block, size_t* rows);
239
240
    Status materialize_pending_predicate_batch(const format::FileScanRequest& request,
241
                                               Block* file_block, size_t* rows);
242
243
    void mark_condition_cache_granules(const SelectionVector& selection, uint16_t selected_rows,
244
                                       int64_t batch_first_file_row);
245
246
    std::vector<RowGroupReadPlan> _row_group_plans; // row group queue to scan
247
    size_t _next_row_group_plan_idx = 0;            // index of the next row group to process
248
249
    bool _has_current_row_group = false;
250
    // Readers retain pointers into this immutable row-group map, so it must outlive both maps below.
251
    std::unordered_map<int, tparquet::OffsetIndex> _current_offset_indexes;
252
    // File-local ids are signed because virtual columns use reserved negative values. Keeping the
253
    // typed id as the map key prevents GLOBAL_ROWID_COLUMN_ID from wrapping to a storage ColumnId.
254
    std::map<format::LocalColumnId, std::unique_ptr<ParquetColumnReader>>
255
            _current_predicate_columns; // predicate ColumnReaders
256
    std::map<format::LocalColumnId, std::unique_ptr<ParquetColumnReader>>
257
            _current_non_predicate_columns; // non-predicate ColumnReaders
258
    std::map<format::LocalColumnId, IColumn::Filter>
259
            _current_dictionary_filters; // local id -> dict entry bitmap
260
    std::map<format::LocalColumnId, std::vector<std::pair<VExprContextSPtr, VExprSPtr>>>
261
            _current_dictionary_residual_conjuncts; // local id -> row-level residual conjuncts
262
    int64_t _current_row_group_rows = 0;            // current row group row count
263
    int _current_row_group_id = -1;                 // current row group id in parquet metadata
264
    int64_t _current_row_group_rows_read = 0;       // rows read in the current row group (cursor)
265
    int64_t _current_row_group_first_row = 0;       // first file row of the current row group
266
    std::vector<RowRange>
267
            _current_selected_ranges; // selected ranges for the current row group after page-index pruning
268
    size_t _current_range_idx = 0;        // current selected_range index
269
    int64_t _current_range_rows_read = 0; // rows read in the current range
270
    // Predicate readers move immediately because they decide which rows survive. Non-predicate
271
    // readers can lag behind across fully filtered batches and range gaps; the lag is flushed once
272
    // before the next surviving batch is materialized, or discarded with the row group.
273
    int64_t _pending_non_predicate_skip_rows = 0;
274
    // Empty predicate batches may widen their physical probe. If the first non-empty probe finds
275
    // more rows than the caller's cap, keep its narrow predicate result here and materialize lazy
276
    // columns in capped physical slices on subsequent calls.
277
    int64_t _pending_predicate_batch_rows = 0;
278
    int64_t _pending_predicate_batch_rows_consumed = 0;
279
    size_t _pending_predicate_selected_offset = 0;
280
    std::vector<SelectionVector::Index> _pending_predicate_selection;
281
    std::map<size_t, ColumnPtr> _pending_predicate_columns;
282
    SelectionVector _pending_output_selection;
283
284
    bool _current_predicate_prefetched = false;
285
    bool _current_non_predicate_prefetched = false;
286
    bool _current_merge_range_active = false;
287
    ParquetPageSkipProfile _page_skip_profile;
288
    ParquetScanProfile _scan_profile;
289
    const ParquetProfile* _parquet_profile = nullptr;
290
    RuntimeProfile* _profile = nullptr;
291
    int64_t _merge_read_slice_size = -1;
292
    std::optional<format::GlobalRowIdContext> _global_rowid_context;
293
    const cctz::time_zone* _timezone = nullptr;
294
    bool _enable_strict_mode = false;
295
    bool _enable_bloom_filter = false;
296
    RuntimeState* _runtime_state = nullptr;
297
    int64_t _batch_size = DEFAULT_READ_BATCH_SIZE;
298
    // Batch control scratch is scheduler-owned so adaptive row caps change logical sizes without
299
    // reallocating selection indices, dense filter bytes, or compacted-column positions.
300
    SelectionVector _selection;
301
    std::vector<uint32_t> _read_column_positions_scratch;
302
    const format::FileScanRequest* _predicate_schedule_request = nullptr;
303
    detail::PredicateConjunctSchedule _predicate_schedule;
304
    std::vector<size_t> _predicate_positions_scratch;
305
    std::unordered_map<size_t, size_t> _predicate_indices_by_position_scratch;
306
    std::vector<size_t> _ordered_predicate_positions_scratch;
307
    std::unordered_map<uint32_t, std::vector<SelectionVector::Index>>
308
            _predicate_column_selection_scratch;
309
    IColumn::Filter _predicate_compaction_filter_scratch;
310
    size_t _predicate_batch_sequence = 0;
311
    size_t _batches_since_profile_flush = 0;
312
    std::unordered_map<size_t, detail::AdaptivePredicateStats> _predicate_runtime_stats;
313
    double _predicate_survival_ratio = -1;
314
    std::shared_ptr<ConditionCacheContext> _condition_cache_ctx;
315
    int64_t _condition_cache_filtered_rows = 0;
316
    int64_t _predicate_filtered_rows = 0;
317
    int64_t _raw_rows_read = 0;
318
};
319
320
} // namespace doris::format::parquet