Coverage Report

Created: 2026-07-24 12:02

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