Coverage Report

Created: 2026-07-15 13:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format_v2/parquet/parquet_reader.cpp
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
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "format_v2/parquet/parquet_reader.h"
19
20
#include <algorithm>
21
#include <map>
22
#include <memory>
23
#include <optional>
24
#include <ranges>
25
#include <unordered_set>
26
#include <utility>
27
#include <vector>
28
29
#include "common/cast_set.h"
30
#include "core/assert_cast.h"
31
#include "core/block/block.h"
32
#include "core/data_type/data_type_array.h"
33
#include "core/data_type/data_type_factory.hpp"
34
#include "core/data_type/data_type_map.h"
35
#include "core/data_type/data_type_nullable.h"
36
#include "core/data_type/data_type_struct.h"
37
#include "format_v2/column_mapper.h"
38
#include "format_v2/parquet/parquet_column_schema.h"
39
#include "format_v2/parquet/parquet_file_context.h"
40
#include "format_v2/parquet/parquet_scan.h"
41
#include "format_v2/parquet/parquet_statistics.h"
42
#include "format_v2/parquet/reader/column_reader.h"
43
#include "io/io_common.h"
44
#include "runtime/runtime_state.h"
45
46
namespace doris::format::parquet {
47
48
struct ParquetReaderScanState {
49
    ParquetFileContext file_context;
50
    std::vector<std::unique_ptr<ParquetColumnSchema>> file_schema;
51
    RowGroupScanPlan scan_plan;
52
    ParquetScanScheduler scheduler;
53
    const RuntimeState* runtime_state = nullptr;
54
    const cctz::time_zone* timezone = nullptr;
55
    bool enable_bloom_filter = false;
56
    bool enable_page_cache = false;
57
    bool enable_strict_mode = false;
58
};
59
60
246
int64_t column_chunk_start_offset(const ::parquet::ColumnChunkMetaData& column_metadata) {
61
246
    return column_metadata.has_dictionary_page()
62
246
                   ? cast_set<int64_t>(column_metadata.dictionary_page_offset())
63
246
                   : cast_set<int64_t>(column_metadata.data_page_offset());
64
246
}
65
66
void collect_all_leaf_column_ids(const ParquetColumnSchema& column_schema,
67
226
                                 std::unordered_set<int>* leaf_column_ids) {
68
226
    DORIS_CHECK(leaf_column_ids != nullptr);
69
226
    if (column_schema.kind == ParquetColumnSchemaKind::PRIMITIVE) {
70
216
        if (column_schema.leaf_column_id >= 0) {
71
216
            leaf_column_ids->insert(column_schema.leaf_column_id);
72
216
        }
73
216
        return;
74
216
    }
75
14
    for (const auto& child : column_schema.children) {
76
14
        DORIS_CHECK(child != nullptr);
77
14
        collect_all_leaf_column_ids(*child, leaf_column_ids);
78
14
    }
79
10
}
80
81
void collect_projected_leaf_column_ids(const ParquetColumnSchema& column_schema,
82
                                       const format::LocalColumnIndex& projection,
83
219
                                       std::unordered_set<int>* leaf_column_ids) {
84
219
    DORIS_CHECK(leaf_column_ids != nullptr);
85
219
    if (projection.project_all_children || projection.children.empty()) {
86
212
        collect_all_leaf_column_ids(column_schema, leaf_column_ids);
87
212
        return;
88
212
    }
89
8
    for (const auto& child_projection : projection.children) {
90
8
        const auto child_it =
91
13
                std::ranges::find_if(column_schema.children, [&](const auto& child_schema) {
92
13
                    return child_schema->local_id == child_projection.local_id();
93
13
                });
94
8
        DORIS_CHECK(child_it != column_schema.children.end());
95
8
        collect_projected_leaf_column_ids(**child_it, child_projection, leaf_column_ids);
96
8
    }
97
7
}
98
99
void collect_request_leaf_column_ids(
100
        const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
101
168
        const format::FileScanRequest& request, std::unordered_set<int>* leaf_column_ids) {
102
168
    DORIS_CHECK(leaf_column_ids != nullptr);
103
242
    auto collect_scan_column = [&](const format::LocalColumnIndex& projection) {
104
242
        const auto local_id = projection.local_id();
105
242
        if (local_id == format::ROW_POSITION_COLUMN_ID ||
106
242
            local_id == format::GLOBAL_ROWID_COLUMN_ID) {
107
31
            return;
108
31
        }
109
211
        DORIS_CHECK(local_id >= 0 && local_id < static_cast<int32_t>(file_schema.size()));
110
211
        DORIS_CHECK(file_schema[local_id] != nullptr);
111
211
        collect_projected_leaf_column_ids(*file_schema[local_id], projection, leaf_column_ids);
112
211
    };
113
168
    for (const auto& column : request.predicate_columns) {
114
88
        collect_scan_column(column);
115
88
    }
116
168
    for (const auto& column : request.non_predicate_columns) {
117
154
        collect_scan_column(column);
118
154
    }
119
168
}
120
121
265
Status validate_all_projected_leaves_supported(const ParquetColumnSchema& column_schema) {
122
265
    if (column_schema.kind == ParquetColumnSchemaKind::PRIMITIVE) {
123
244
        if (!column_schema.type_descriptor.unsupported_reason.empty()) {
124
1
            return Status::NotSupported("Unsupported parquet column '{}': {}", column_schema.name,
125
1
                                        column_schema.type_descriptor.unsupported_reason);
126
1
        }
127
243
        return Status::OK();
128
244
    }
129
31
    for (const auto& child : column_schema.children) {
130
31
        DORIS_CHECK(child != nullptr);
131
31
        RETURN_IF_ERROR(validate_all_projected_leaves_supported(*child));
132
31
    }
133
21
    return Status::OK();
134
21
}
135
136
Status validate_projected_leaves_supported(const ParquetColumnSchema& column_schema,
137
243
                                           const format::LocalColumnIndex& projection) {
138
243
    if (column_schema.kind == ParquetColumnSchemaKind::PRIMITIVE ||
139
243
        projection.project_all_children || projection.children.empty()) {
140
234
        return validate_all_projected_leaves_supported(column_schema);
141
234
    }
142
10
    for (const auto& child_projection : projection.children) {
143
10
        const auto child_it =
144
15
                std::ranges::find_if(column_schema.children, [&](const auto& child_schema) {
145
15
                    return child_schema->local_id == child_projection.local_id();
146
15
                });
147
10
        DORIS_CHECK(child_it != column_schema.children.end());
148
10
        RETURN_IF_ERROR(validate_projected_leaves_supported(**child_it, child_projection));
149
10
    }
150
9
    return Status::OK();
151
9
}
152
153
Status validate_requested_columns_supported(
154
        const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
155
168
        const format::FileScanRequest& request) {
156
242
    auto validate_scan_column = [&](const format::LocalColumnIndex& projection) -> Status {
157
242
        const auto local_id = projection.local_id();
158
242
        if (local_id == format::ROW_POSITION_COLUMN_ID ||
159
242
            local_id == format::GLOBAL_ROWID_COLUMN_ID) {
160
31
            return Status::OK();
161
31
        }
162
211
        DORIS_CHECK(local_id >= 0 && local_id < static_cast<int32_t>(file_schema.size()));
163
211
        DORIS_CHECK(file_schema[local_id] != nullptr);
164
211
        return validate_projected_leaves_supported(*file_schema[local_id], projection);
165
242
    };
166
168
    for (const auto& column : request.predicate_columns) {
167
88
        RETURN_IF_ERROR(validate_scan_column(column));
168
88
    }
169
168
    for (const auto& column : request.non_predicate_columns) {
170
154
        RETURN_IF_ERROR(validate_scan_column(column));
171
154
    }
172
168
    return Status::OK();
173
168
}
174
175
std::vector<ParquetPageCacheRange> build_page_cache_ranges(
176
        const ::parquet::FileMetaData& metadata,
177
        const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
178
168
        const format::FileScanRequest& request, const RowGroupScanPlan& row_group_plan) {
179
168
    std::unordered_set<int> leaf_column_ids;
180
168
    collect_request_leaf_column_ids(file_schema, request, &leaf_column_ids);
181
168
    std::vector<ParquetPageCacheRange> ranges;
182
168
    ranges.reserve(row_group_plan.row_groups.size() * leaf_column_ids.size());
183
195
    for (const auto& row_group_plan_item : row_group_plan.row_groups) {
184
195
        auto row_group_metadata = metadata.RowGroup(row_group_plan_item.row_group_id);
185
195
        DORIS_CHECK(row_group_metadata != nullptr);
186
246
        for (const auto leaf_column_id : leaf_column_ids) {
187
246
            DORIS_CHECK(leaf_column_id >= 0 && leaf_column_id < row_group_metadata->num_columns());
188
246
            auto column_metadata = row_group_metadata->ColumnChunk(leaf_column_id);
189
246
            DORIS_CHECK(column_metadata != nullptr);
190
246
            const int64_t offset = column_chunk_start_offset(*column_metadata);
191
246
            const int64_t size = column_metadata->total_compressed_size();
192
246
            DORIS_CHECK(offset >= 0);
193
246
            DORIS_CHECK(size >= 0);
194
246
            if (size > 0) {
195
246
                ranges.push_back(ParquetPageCacheRange {.offset = offset, .size = size});
196
246
            }
197
246
        }
198
195
    }
199
168
    return ranges;
200
168
}
201
202
const ParquetColumnSchema& projected_root_schema(
203
        const std::vector<std::unique_ptr<ParquetColumnSchema>>& file_schema,
204
8
        const format::LocalColumnIndex& projection) {
205
8
    const auto local_id = projection.local_id();
206
8
    DORIS_CHECK(local_id >= 0 && local_id < static_cast<int32_t>(file_schema.size()));
207
8
    DORIS_CHECK(file_schema[local_id] != nullptr);
208
8
    return *file_schema[local_id];
209
8
}
210
211
int64_t count_loaded_non_null_values(const ParquetColumnSchema& root_schema,
212
                                     const ParquetColumnReader& shape_reader,
213
7
                                     int64_t expected_rows) {
214
7
    const auto& def_levels = shape_reader.nested_definition_levels();
215
7
    const auto& rep_levels = shape_reader.nested_repetition_levels();
216
7
    const int64_t levels_written = shape_reader.nested_levels_written();
217
7
    DORIS_CHECK(levels_written >= expected_rows);
218
7
    if (root_schema.max_repetition_level == 0) {
219
3
        DORIS_CHECK(levels_written == expected_rows);
220
3
        const int16_t non_null_definition_level = root_schema.nullable_definition_level;
221
3
        int64_t count = 0;
222
12
        for (int64_t level_idx = 0; level_idx < levels_written; ++level_idx) {
223
9
            count += def_levels[level_idx] >= non_null_definition_level ? 1 : 0;
224
9
        }
225
3
        return count;
226
3
    }
227
228
    // For repeated encodings, repetition level zero starts a top-level row. Empty MAP/LIST rows
229
    // have no entries but still carry a level slot; they are non-NULL and must be counted by
230
    // count(col). The root nullable level distinguishes a NULL top-level value from a non-NULL
231
    // value regardless of which repeated leaf represents its shape.
232
4
    const int16_t non_null_definition_level = root_schema.nullable_definition_level;
233
4
    int64_t counted_rows = 0;
234
4
    int64_t non_null_rows = 0;
235
26
    for (int64_t level_idx = 0; level_idx < levels_written && counted_rows < expected_rows;
236
22
         ++level_idx) {
237
22
        if (rep_levels[level_idx] != 0) {
238
2
            continue;
239
2
        }
240
20
        ++counted_rows;
241
20
        non_null_rows += def_levels[level_idx] >= non_null_definition_level ? 1 : 0;
242
20
    }
243
4
    DORIS_CHECK(counted_rows == expected_rows);
244
4
    return non_null_rows;
245
7
}
246
247
0
DataTypePtr nullable_like_original(const DataTypePtr& type, DataTypePtr nested_type) {
248
0
    return type != nullptr && type->is_nullable() ? make_nullable(nested_type) : nested_type;
249
0
}
250
251
3
int timestamp_tz_scale(const ParquetTypeDescriptor& type_descriptor) {
252
3
    switch (type_descriptor.time_unit) {
253
0
    case ParquetTimeUnit::MILLIS:
254
0
        return 3;
255
2
    case ParquetTimeUnit::MICROS:
256
3
    case ParquetTimeUnit::UNKNOWN:
257
3
    default:
258
3
        return 6;
259
3
    }
260
3
}
261
262
4
bool should_map_to_timestamp_tz(const ParquetColumnSchema& column_schema) {
263
4
    const auto& type_descriptor = column_schema.type_descriptor;
264
4
    return type_descriptor.physical_type == ::parquet::Type::INT96 ||
265
4
           (type_descriptor.is_timestamp && type_descriptor.timestamp_is_adjusted_to_utc);
266
4
}
267
268
4
DataTypePtr apply_timestamp_tz_mapping(ParquetColumnSchema* column_schema) {
269
4
    DORIS_CHECK(column_schema != nullptr);
270
4
    if (column_schema->kind == ParquetColumnSchemaKind::PRIMITIVE) {
271
4
        if (should_map_to_timestamp_tz(*column_schema)) {
272
3
            const bool nullable =
273
3
                    column_schema->type != nullptr && column_schema->type->is_nullable();
274
3
            const auto scale = timestamp_tz_scale(column_schema->type_descriptor);
275
3
            column_schema->type = DataTypeFactory::instance().create_data_type(TYPE_TIMESTAMPTZ,
276
3
                                                                               nullable, 0, scale);
277
3
            column_schema->type_descriptor.doris_type = column_schema->type;
278
3
        }
279
4
        return column_schema->type;
280
4
    }
281
282
0
    std::vector<DataTypePtr> child_types;
283
0
    child_types.reserve(column_schema->children.size());
284
0
    for (auto& child : column_schema->children) {
285
0
        child_types.push_back(apply_timestamp_tz_mapping(child.get()));
286
0
    }
287
288
0
    if (column_schema->kind == ParquetColumnSchemaKind::LIST) {
289
0
        DORIS_CHECK(child_types.size() == 1);
290
0
        column_schema->type = nullable_like_original(
291
0
                column_schema->type, std::make_shared<DataTypeArray>(child_types[0]));
292
0
    } else if (column_schema->kind == ParquetColumnSchemaKind::MAP) {
293
0
        DORIS_CHECK(child_types.size() == 2);
294
0
        column_schema->type = nullable_like_original(
295
0
                column_schema->type, std::make_shared<DataTypeMap>(make_nullable(child_types[0]),
296
0
                                                                   make_nullable(child_types[1])));
297
0
    } else if (column_schema->kind == ParquetColumnSchemaKind::STRUCT) {
298
0
        Strings child_names;
299
0
        child_names.reserve(column_schema->children.size());
300
0
        for (const auto& child : column_schema->children) {
301
0
            child_names.push_back(child->name);
302
0
        }
303
0
        column_schema->type = nullable_like_original(
304
0
                column_schema->type, std::make_shared<DataTypeStruct>(child_types, child_names));
305
0
    }
306
0
    return column_schema->type;
307
4
}
308
309
static Status find_projected_minmax_leaf(const ParquetColumnSchema& column_schema,
310
                                         const format::LocalColumnIndex& projection,
311
15
                                         const ParquetColumnSchema** leaf_schema) {
312
15
    DORIS_CHECK(leaf_schema != nullptr);
313
15
    if (projection.project_all_children || projection.children.empty()) {
314
13
        if (column_schema.leaf_column_id < 0) {
315
2
            return Status::NotSupported(
316
2
                    "Parquet aggregate pushdown only supports primitive column {}",
317
2
                    column_schema.name);
318
2
        }
319
11
        if (column_schema.max_repetition_level > 0) {
320
0
            return Status::NotSupported(
321
0
                    "Parquet aggregate pushdown does not support repeated column {}",
322
0
                    column_schema.name);
323
0
        }
324
11
        *leaf_schema = &column_schema;
325
11
        return Status::OK();
326
11
    }
327
2
    if (projection.children.size() != 1) {
328
0
        return Status::NotSupported(
329
0
                "Parquet aggregate pushdown only supports a single nested leaf under column {}",
330
0
                column_schema.name);
331
0
    }
332
2
    const auto& child_projection = projection.children[0];
333
2
    const auto child_schema_it =
334
2
            std::ranges::find_if(column_schema.children, [&](const auto& child_schema) {
335
2
                return child_schema->local_id == child_projection.local_id();
336
2
            });
337
2
    if (child_schema_it != column_schema.children.end()) {
338
2
        return find_projected_minmax_leaf(**child_schema_it, child_projection, leaf_schema);
339
2
    }
340
0
    return Status::InvalidArgument("Invalid parquet aggregate projection local id {} for column {}",
341
0
                                   child_projection.local_id(), column_schema.name);
342
2
}
343
344
11
static Status validate_minmax_aggregate_statistics(const ParquetColumnSchema& column_schema) {
345
11
    DORIS_CHECK(column_schema.descriptor != nullptr);
346
11
    switch (column_schema.descriptor->physical_type()) {
347
1
    case ::parquet::Type::BYTE_ARRAY:
348
2
    case ::parquet::Type::FIXED_LEN_BYTE_ARRAY:
349
        // Arrow 17 does not expose Parquet's min/max exactness flags. Binary statistics may be
350
        // truncated bounds rather than values present in the file, so they are safe for pruning
351
        // but cannot be returned as exact aggregate results.
352
2
        return Status::NotSupported(
353
2
                "Parquet MIN/MAX aggregate pushdown requires exact statistics for column {}",
354
2
                column_schema.name);
355
9
    default:
356
9
        return Status::OK();
357
11
    }
358
11
}
359
360
void ParquetReader::_fill_column_definition(const ParquetColumnSchema& column_schema,
361
338
                                            format::ColumnDefinition* field) const {
362
338
    if (column_schema.parquet_field_id >= 0) {
363
140
        field->identifier = Field::create_field<TYPE_INT>(column_schema.parquet_field_id);
364
198
    } else {
365
198
        field->identifier = Field::create_field<TYPE_STRING>(column_schema.name);
366
198
    }
367
338
    field->local_id = column_schema.local_id;
368
338
    field->name = column_schema.name;
369
338
    field->type = column_schema.type != nullptr && !column_schema.type->is_nullable()
370
338
                          ? make_nullable(column_schema.type)
371
338
                          : column_schema.type;
372
338
    field->children.clear();
373
338
    field->children.reserve(column_schema.children.size());
374
338
    for (const auto& child : column_schema.children) {
375
29
        format::ColumnDefinition child_field;
376
29
        _fill_column_definition(*child, &child_field);
377
29
        field->children.push_back(std::move(child_field));
378
29
    }
379
338
}
380
381
ParquetReader::ParquetReader(std::shared_ptr<io::FileSystemProperties>& system_properties,
382
                             std::unique_ptr<io::FileDescription>& file_description,
383
                             std::shared_ptr<io::IOContext> io_ctx, RuntimeProfile* profile,
384
                             std::optional<format::GlobalRowIdContext> global_rowid_context,
385
                             bool enable_mapping_timestamp_tz)
386
173
        : FileReader(system_properties, file_description, io_ctx, profile),
387
173
          _global_rowid_context(global_rowid_context),
388
173
          _enable_mapping_timestamp_tz(enable_mapping_timestamp_tz) {}
389
390
173
ParquetReader::~ParquetReader() = default;
391
392
172
Status ParquetReader::init(RuntimeState* state) {
393
172
    if (_io_ctx != nullptr && _io_ctx->should_stop) {
394
0
        return Status::EndOfFile("stop");
395
0
    }
396
172
    RETURN_IF_ERROR(format::FileReader::init(state));
397
172
    if (_profile != nullptr) {
398
81
        COUNTER_UPDATE(_parquet_profile.file_reader_create_time,
399
81
                       _reader_statistics.file_reader_create_time);
400
81
        COUNTER_UPDATE(_parquet_profile.open_file_num, _reader_statistics.open_file_num);
401
81
    }
402
172
    _state = std::make_unique<ParquetReaderScanState>();
403
172
    _state->enable_bloom_filter =
404
172
            state != nullptr && state->query_options().enable_parquet_filter_by_bloom_filter;
405
172
    _state->enable_page_cache =
406
172
            state != nullptr && state->query_options().enable_parquet_file_page_cache;
407
172
    if (state != nullptr) {
408
172
        _state->runtime_state = state;
409
172
        _state->timezone = &state->timezone_obj();
410
172
        _state->enable_strict_mode = state->enable_strict_mode();
411
172
        _state->scheduler.set_timezone(&state->timezone_obj());
412
172
        _state->scheduler.set_enable_strict_mode(_state->enable_strict_mode);
413
172
    }
414
172
    int64_t merge_read_slice_size = -1;
415
172
    if (state != nullptr && state->query_options().__isset.merge_read_slice_size) {
416
172
        merge_read_slice_size = state->query_options().merge_read_slice_size;
417
172
    }
418
172
    _state->scheduler.set_merge_read_options(_profile, merge_read_slice_size);
419
172
    _state->scheduler.set_batch_size(_batch_size);
420
    // Open parquet file and parse metadata to get file schema.
421
172
    RETURN_IF_ERROR(_state->file_context.open(_tracing_file_reader, _io_ctx.get(),
422
172
                                              _state->enable_page_cache, *_file_description));
423
    // Build file schema from parquet metadata.
424
    // A file reader may expose raw file identifiers, such as Parquet field_id, through ColumnDefinition::identifier
425
172
    RETURN_IF_ERROR(
426
172
            build_parquet_column_schema(*_state->file_context.schema, &_state->file_schema));
427
172
    if (_enable_mapping_timestamp_tz) {
428
4
        for (auto& column_schema : _state->file_schema) {
429
4
            apply_timestamp_tz_mapping(column_schema.get());
430
4
        }
431
3
    }
432
172
    return Status::OK();
433
172
}
434
435
4
void ParquetReader::set_batch_size(size_t batch_size) {
436
4
    _batch_size = std::max<size_t>(1, batch_size);
437
4
    if (_state != nullptr) {
438
0
        _state->scheduler.set_batch_size(_batch_size);
439
0
    }
440
4
}
441
442
156
Status ParquetReader::get_schema(std::vector<format::ColumnDefinition>* file_schema) const {
443
156
    if (file_schema == nullptr) {
444
0
        return Status::InvalidArgument("file_schema is null");
445
0
    }
446
156
    file_schema->clear();
447
156
    if (_state == nullptr || _state->file_context.schema == nullptr) {
448
0
        return Status::Uninitialized("ParquetReader is not open");
449
0
    }
450
451
156
    file_schema->reserve(_state->file_schema.size());
452
465
    for (size_t column_idx = 0; column_idx < _state->file_schema.size(); ++column_idx) {
453
309
        format::ColumnDefinition field;
454
309
        _fill_column_definition(*_state->file_schema[column_idx], &field);
455
309
        DORIS_CHECK(field.local_id == static_cast<int32_t>(column_idx));
456
309
        file_schema->push_back(std::move(field));
457
309
    }
458
156
    if (_global_rowid_context.has_value()) {
459
2
        file_schema->push_back(format::global_rowid_column_definition());
460
2
    }
461
156
    return Status::OK();
462
156
}
463
464
std::unique_ptr<format::TableColumnMapper> ParquetReader::create_column_mapper(
465
82
        format::TableColumnMapperOptions options) const {
466
82
    return std::make_unique<format::ParquetColumnMapper>(std::move(options));
467
82
}
468
469
168
Status ParquetReader::open(std::shared_ptr<format::FileScanRequest> request) {
470
168
    if (_state == nullptr || _state->file_context.metadata == nullptr ||
471
168
        _state->file_context.schema == nullptr) {
472
0
        return Status::Uninitialized("ParquetReader is not open");
473
0
    }
474
168
    auto request_snapshot = request;
475
168
    DORIS_CHECK(request_snapshot != nullptr);
476
168
    RETURN_IF_ERROR(format::FileReader::open(std::move(request)));
477
478
    // `local_positions.empty()` means all columns are needed by table reader
479
    // TODO(gabriel): It will happen only for TVF `select *` query.
480
168
    if (request_snapshot->local_positions.empty()) {
481
38
        for (const auto& col : request_snapshot->predicate_columns) {
482
13
            request_snapshot->local_positions.emplace(col.column_id(),
483
13
                                                      format::LocalIndex(col.column_id().value()));
484
13
        }
485
38
        for (const auto& col : request_snapshot->non_predicate_columns) {
486
19
            request_snapshot->local_positions.emplace(col.column_id(),
487
19
                                                      format::LocalIndex(col.column_id().value()));
488
19
        }
489
38
    }
490
491
168
    const auto num_fields = static_cast<int32_t>(_state->file_schema.size());
492
168
    for (const auto& col : request_snapshot->predicate_columns) {
493
88
        DORIS_CHECK(request_snapshot->local_positions.count(col.column_id()) > 0);
494
88
        const auto local_id = col.local_id();
495
88
        if (local_id == format::ROW_POSITION_COLUMN_ID ||
496
88
            local_id == format::GLOBAL_ROWID_COLUMN_ID) {
497
17
            continue;
498
17
        }
499
71
        DORIS_CHECK(local_id >= 0 && local_id < num_fields);
500
71
    }
501
168
    for (const auto& col : request_snapshot->non_predicate_columns) {
502
154
        DORIS_CHECK(request_snapshot->local_positions.count(col.column_id()) > 0);
503
154
        const auto local_id = col.local_id();
504
154
        if (local_id == format::ROW_POSITION_COLUMN_ID ||
505
154
            local_id == format::GLOBAL_ROWID_COLUMN_ID) {
506
14
            continue;
507
14
        }
508
140
        DORIS_CHECK(local_id >= 0 && local_id < num_fields);
509
140
    }
510
511
    // Reject requested unsupported logical leaves before row-group statistics, dictionaries,
512
    // bloom filters or page indexes inspect their physical fallback type. For example, a predicate
513
    // on TIME_MILLIS must fail here even when its INT32 statistics would prune every row group;
514
    // otherwise the same unsupported SELECT could fail or silently succeed depending on data.
515
168
    RETURN_IF_ERROR(validate_requested_columns_supported(_state->file_schema, *request_snapshot));
516
517
168
    RowGroupScanPlan row_group_plan;
518
168
    ParquetScanRange scan_range;
519
168
    scan_range.start_offset = _file_description->range_start_offset;
520
168
    scan_range.size = _file_description->range_size;
521
168
    scan_range.file_size = _file_description->file_size;
522
    // Get selected ranges in row groups according to metadata (Row-Group level index and Page Index including Zonemap, Dictionary, Bloom Filter).
523
168
    RETURN_IF_ERROR(plan_parquet_row_groups(
524
168
            *_state->file_context.metadata, _state->file_context.file_reader.get(),
525
168
            _state->file_schema, *request_snapshot, scan_range, _state->enable_bloom_filter,
526
168
            &row_group_plan, _state->timezone, _state->runtime_state));
527
168
    if (_profile != nullptr) {
528
81
        _parquet_profile.update_pruning_stats(row_group_plan.pruning_stats);
529
81
    }
530
168
    if (_state->enable_page_cache) {
531
168
        _state->file_context.register_page_cache_ranges(
532
168
                build_page_cache_ranges(*_state->file_context.metadata, _state->file_schema,
533
168
                                        *request_snapshot, row_group_plan));
534
168
    }
535
168
    _state->scan_plan = row_group_plan;
536
168
    _state->scheduler.set_page_skip_profile(_parquet_profile.page_skip_profile());
537
168
    _state->scheduler.set_global_rowid_context(_global_rowid_context);
538
168
    _state->scheduler.set_scan_profile(_parquet_profile.scan_profile());
539
168
    _state->scheduler.set_plan(std::move(row_group_plan));
540
168
    _eof = _state->scheduler.empty();
541
168
    return Status::OK();
542
168
}
543
544
249
Status ParquetReader::get_block(Block* file_block, size_t* rows, bool* eof) {
545
249
    if (_state == nullptr || _state->file_context.file_reader == nullptr ||
546
249
        _state->file_context.schema == nullptr) {
547
0
        return Status::Uninitialized("ParquetReader is not open");
548
0
    }
549
249
    *rows = 0;
550
249
    if (_io_ctx != nullptr && _io_ctx->should_stop) {
551
0
        *eof = true;
552
0
        return Status::OK();
553
0
    }
554
249
    if (_eof) {
555
2
        *eof = true;
556
2
        return Status::OK();
557
2
    }
558
247
    auto request_snapshot = _request;
559
247
    if (request_snapshot == nullptr) {
560
0
        return Status::Cancelled("ParquetReader is closed");
561
0
    }
562
563
247
    const auto predicate_filtered_rows_before = _state->scheduler.predicate_filtered_rows();
564
247
    const auto raw_rows_read_before = _state->scheduler.raw_rows_read();
565
247
    Status st = _state->scheduler.read_next_batch(_state->file_context, _state->file_schema,
566
247
                                                  *request_snapshot, file_block, rows, eof);
567
247
    if (!st.ok()) {
568
0
        if (_io_ctx != nullptr && _io_ctx->should_stop) {
569
0
            *rows = 0;
570
0
            *eof = true;
571
0
            return Status::OK();
572
0
        }
573
0
        return st;
574
0
    }
575
247
    _sync_page_cache_profile();
576
247
    if (_io_ctx != nullptr) {
577
106
        _io_ctx->predicate_filtered_rows +=
578
106
                _state->scheduler.predicate_filtered_rows() - predicate_filtered_rows_before;
579
106
    }
580
247
    const auto raw_rows_read = _state->scheduler.raw_rows_read();
581
247
    DORIS_CHECK(raw_rows_read >= raw_rows_read_before);
582
247
    _record_scan_rows(raw_rows_read - raw_rows_read_before);
583
247
    _eof = *eof;
584
247
    return Status::OK();
585
247
}
586
587
27
bool ParquetReader::_should_stop() const {
588
27
    return _io_ctx != nullptr && _io_ctx->should_stop;
589
27
}
590
591
14
Status ParquetReader::_stop_status_if_requested(const Status& status) const {
592
14
    if (!status.ok() && _should_stop()) {
593
0
        return Status::EndOfFile("stop");
594
0
    }
595
14
    return status;
596
14
}
597
598
353
void ParquetReader::_sync_page_cache_profile() {
599
353
    if (_profile == nullptr || _state == nullptr) {
600
155
        return;
601
155
    }
602
198
    const auto stats = _state->file_context.page_cache_stats();
603
198
    COUNTER_UPDATE(_parquet_profile.page_read_counter,
604
198
                   stats.read_count - _reported_page_cache_stats.read_count);
605
198
    COUNTER_UPDATE(_parquet_profile.page_cache_write_counter,
606
198
                   stats.write_count - _reported_page_cache_stats.write_count);
607
198
    COUNTER_UPDATE(
608
198
            _parquet_profile.page_cache_compressed_write_counter,
609
198
            stats.compressed_write_count - _reported_page_cache_stats.compressed_write_count);
610
198
    COUNTER_UPDATE(_parquet_profile.page_cache_hit_counter,
611
198
                   stats.hit_count - _reported_page_cache_stats.hit_count);
612
198
    COUNTER_UPDATE(_parquet_profile.page_cache_missing_counter,
613
198
                   stats.miss_count - _reported_page_cache_stats.miss_count);
614
198
    COUNTER_UPDATE(_parquet_profile.page_cache_compressed_hit_counter,
615
198
                   stats.compressed_hit_count - _reported_page_cache_stats.compressed_hit_count);
616
198
    _reported_page_cache_stats = stats;
617
198
}
618
619
2
void ParquetReader::set_condition_cache_context(std::shared_ptr<ConditionCacheContext> ctx) {
620
2
    if (_state == nullptr) {
621
0
        return;
622
0
    }
623
2
    _state->scheduler.set_condition_cache_context(std::move(ctx));
624
2
    if (_io_ctx != nullptr) {
625
        // Condition-cache HIT filters row ranges before batch reading, so skipped rows never belong
626
        // to a later get_block() batch. Report the plan-level skipped rows at the same point where
627
        // the scan plan is rewritten.
628
1
        _io_ctx->condition_cache_filtered_rows += _state->scheduler.condition_cache_filtered_rows();
629
1
    }
630
2
}
631
632
0
int64_t ParquetReader::get_total_rows() const {
633
0
    if (_state == nullptr) {
634
0
        return 0;
635
0
    }
636
0
    int64_t rows = 0;
637
0
    for (const auto& row_group_plan : _state->scan_plan.row_groups) {
638
0
        rows += row_group_plan.row_group_rows;
639
0
    }
640
0
    return rows;
641
0
}
642
643
Status ParquetReader::get_aggregate_result(const format::FileAggregateRequest& request,
644
27
                                           format::FileAggregateResult* result) {
645
27
    DORIS_CHECK(result != nullptr);
646
27
    if (_state == nullptr || _state->file_context.metadata == nullptr ||
647
27
        _state->file_context.schema == nullptr) {
648
0
        return Status::Uninitialized("ParquetReader is not open");
649
0
    }
650
27
    if (_should_stop()) {
651
1
        return Status::EndOfFile("stop");
652
1
    }
653
26
    result->count = 0;
654
26
    result->columns.clear();
655
26
    if (request.agg_type != TPushAggOp::type::COUNT &&
656
26
        request.agg_type != TPushAggOp::type::MINMAX) {
657
1
        return Status::NotSupported("Unsupported parquet aggregate pushdown type {}",
658
1
                                    request.agg_type);
659
1
    }
660
661
25
    for (const auto& aggregate_column : request.columns) {
662
23
        const auto local_id = aggregate_column.projection.local_id();
663
23
        if (local_id < 0 || local_id >= static_cast<int32_t>(_state->file_schema.size())) {
664
1
            return Status::InvalidArgument("Invalid parquet aggregate column id {}", local_id);
665
1
        }
666
22
        DORIS_CHECK(_state->file_schema[local_id] != nullptr);
667
        // Aggregate pushdown can return directly from footer statistics without constructing a
668
        // column reader. Validate first so MIN/MAX(TIME_MILLIS), or an all-pruned COUNT request,
669
        // cannot expose the physical INT32 fallback as a supported logical value.
670
22
        RETURN_IF_ERROR(validate_projected_leaves_supported(*_state->file_schema[local_id],
671
22
                                                            aggregate_column.projection));
672
22
    }
673
674
    // Aggregate row count in all selected row groups. For MIN/MAX aggregate, this is used to determine whether there is no row group selected.
675
38
    for (const auto& row_group_plan : _state->scan_plan.row_groups) {
676
38
        auto row_group_metadata =
677
38
                _state->file_context.metadata->RowGroup(row_group_plan.row_group_id);
678
38
        DORIS_CHECK(row_group_metadata != nullptr);
679
38
        result->count += row_group_metadata->num_rows();
680
38
    }
681
23
    if (request.agg_type == TPushAggOp::type::COUNT) {
682
12
        if (request.columns.empty()) {
683
4
            return Status::OK();
684
4
        }
685
8
        if (request.columns.size() != 1) {
686
0
            return Status::NotSupported("Parquet COUNT pushdown only supports one count column");
687
0
        }
688
8
        const auto& count_projection = request.columns[0].projection;
689
8
        const auto& root_schema = projected_root_schema(_state->file_schema, count_projection);
690
        // A required primitive COUNT(col) still carries its projection so the unsupported-type
691
        // validation above cannot be bypassed. Once validated, its definition level proves that
692
        // every selected row is non-NULL, so preserve the already-computed footer row count and
693
        // avoid reading definition levels merely to rediscover COUNT(col) == COUNT(*). Complex
694
        // roots continue through the shape reader because their count semantics and read-row
695
        // accounting are derived from nested levels.
696
8
        if (root_schema.kind == ParquetColumnSchemaKind::PRIMITIVE &&
697
8
            root_schema.max_definition_level == 0) {
698
2
            return Status::OK();
699
2
        }
700
6
        result->count = 0;
701
7
        for (const auto& row_group_plan : _state->scan_plan.row_groups) {
702
7
            std::shared_ptr<::parquet::RowGroupReader> row_group;
703
7
            try {
704
7
                row_group = _state->file_context.file_reader->RowGroup(row_group_plan.row_group_id);
705
7
            } catch (const ::parquet::ParquetException& e) {
706
0
                if (_should_stop()) {
707
0
                    return Status::EndOfFile("stop");
708
0
                }
709
0
                return Status::Corruption("Failed to open parquet row group {}: {}",
710
0
                                          row_group_plan.row_group_id, e.what());
711
0
            } catch (const std::exception& e) {
712
0
                if (_should_stop()) {
713
0
                    return Status::EndOfFile("stop");
714
0
                }
715
0
                return Status::InternalError("Failed to open parquet row group {}: {}",
716
0
                                             row_group_plan.row_group_id, e.what());
717
0
            }
718
719
7
            ParquetColumnReaderFactory column_reader_factory(
720
7
                    row_group, _state->file_context.schema->num_columns(),
721
7
                    &row_group_plan.page_skip_plans, _parquet_profile.page_skip_profile(),
722
7
                    _state->timezone, _state->enable_strict_mode,
723
7
                    _parquet_profile.scan_profile().column_reader_profile);
724
7
            std::unique_ptr<ParquetColumnReader> shape_reader;
725
7
            RETURN_IF_ERROR(column_reader_factory.create_count_shape_reader(
726
7
                    root_schema, &count_projection, &shape_reader));
727
7
            DORIS_CHECK(shape_reader != nullptr);
728
729
7
            int64_t row_group_cursor = 0;
730
7
            for (const auto& selected_range : row_group_plan.selected_ranges) {
731
7
                DORIS_CHECK(selected_range.start >= row_group_cursor);
732
7
                RETURN_IF_ERROR(_stop_status_if_requested(
733
7
                        shape_reader->skip(selected_range.start - row_group_cursor)));
734
7
                row_group_cursor = selected_range.start;
735
736
7
                int64_t range_rows_read = 0;
737
14
                while (range_rows_read < selected_range.length) {
738
7
                    const int64_t batch_rows =
739
7
                            std::min<int64_t>(_batch_size, selected_range.length - range_rows_read);
740
                    // COUNT(col) only needs the top-level NULL state. The shape reader loads
741
                    // def/rep levels from one representative leaf and does not build value_indices
742
                    // or values_column. MAP chooses the key leaf; ARRAY/STRUCT may choose a string
743
                    // leaf, but the levels-only protocol still avoids Doris-side string
744
                    // materialization for that leaf.
745
7
                    RETURN_IF_ERROR(_stop_status_if_requested(
746
7
                            shape_reader->load_nested_levels_batch(batch_rows)));
747
7
                    _record_scan_rows(batch_rows);
748
7
                    result->count +=
749
7
                            count_loaded_non_null_values(root_schema, *shape_reader, batch_rows);
750
7
                    range_rows_read += batch_rows;
751
7
                    row_group_cursor += batch_rows;
752
7
                }
753
7
            }
754
7
        }
755
6
        return Status::OK();
756
6
    }
757
758
11
    result->columns.resize(request.columns.size());
759
19
    for (size_t request_column_idx = 0; request_column_idx < request.columns.size();
760
13
         ++request_column_idx) {
761
13
        const auto file_column_id = request.columns[request_column_idx].projection.local_id();
762
13
        if (file_column_id < 0 ||
763
13
            file_column_id >= static_cast<int32_t>(_state->file_schema.size())) {
764
0
            return Status::InvalidArgument("Invalid parquet aggregate column id {}",
765
0
                                           file_column_id);
766
0
        }
767
13
        const auto& column_schema = _state->file_schema[file_column_id];
768
13
        DORIS_CHECK(column_schema != nullptr);
769
13
        const ParquetColumnSchema* leaf_schema = nullptr;
770
13
        RETURN_IF_ERROR(find_projected_minmax_leaf(
771
13
                *column_schema, request.columns[request_column_idx].projection, &leaf_schema));
772
11
        DORIS_CHECK(leaf_schema != nullptr);
773
11
        RETURN_IF_ERROR(validate_minmax_aggregate_statistics(*leaf_schema));
774
775
9
        auto& aggregate_column = result->columns[request_column_idx];
776
9
        aggregate_column.projection = request.columns[request_column_idx].projection;
777
17
        for (const auto& row_group_plan : _state->scan_plan.row_groups) {
778
17
            auto row_group_metadata =
779
17
                    _state->file_context.metadata->RowGroup(row_group_plan.row_group_id);
780
17
            DORIS_CHECK(row_group_metadata != nullptr);
781
17
            auto column_chunk = row_group_metadata->ColumnChunk(leaf_schema->leaf_column_id);
782
17
            DORIS_CHECK(column_chunk != nullptr);
783
17
            const auto statistics = ParquetStatisticsUtils::TransformColumnStatistics(
784
17
                    *leaf_schema, column_chunk->statistics(), _state->timezone);
785
17
            if (!statistics.has_min_max) {
786
1
                return Status::NotSupported("Missing parquet min/max statistics for column {}",
787
1
                                            leaf_schema->name);
788
1
            }
789
16
            if (!aggregate_column.has_min || statistics.min_value < aggregate_column.min_value) {
790
8
                aggregate_column.min_value = statistics.min_value;
791
8
                aggregate_column.has_min = true;
792
8
            }
793
16
            if (!aggregate_column.has_max || aggregate_column.max_value < statistics.max_value) {
794
16
                aggregate_column.max_value = statistics.max_value;
795
16
                aggregate_column.has_max = true;
796
16
            }
797
16
        }
798
8
        if (!aggregate_column.has_min || !aggregate_column.has_max) {
799
0
            return Status::NotSupported("No parquet row group selected for min/max pushdown");
800
0
        }
801
8
    }
802
6
    return Status::OK();
803
11
}
804
805
106
Status ParquetReader::close() {
806
106
    if (_state != nullptr) {
807
106
        _sync_page_cache_profile();
808
106
        RETURN_IF_ERROR(_state->file_context.close());
809
106
    }
810
106
    return FileReader::close();
811
106
}
812
813
172
void ParquetReader::_init_profile() {
814
172
    _parquet_profile.init(_profile);
815
172
}
816
817
} // namespace doris::format::parquet