diff --git a/docs/design/parquet-v3-page-level-constant-column.md b/docs/design/parquet-v3-page-level-constant-column.md new file mode 100644 index 0000000000000..dc5224e7dd690 --- /dev/null +++ b/docs/design/parquet-v3-page-level-constant-column.md @@ -0,0 +1,114 @@ +# Parquet v3: per-subgroup (page-level) constant-column detection + +## Motivation + +The current constant-column optimization (`detectConstantColumn`) fires only when a whole +Parquet **column chunk** is single-valued (footer `min == max`, no nulls). Data that is sorted or +clustered on a column is often constant over long **runs of pages** without the whole row group +being constant, so chunk-level detection misses it. + +Parquet's **Column Index** stores per-page `min_values` / `max_values` / `null_pages` / +`null_counts`. The v3 reader already loads and parses it (`applyColumnIndex`) for predicate +push-down, so per-page "is this page constant?" is available at zero extra I/O. This lets us mark a +column constant for the row range of an individual **row subgroup** (the unit that becomes one +output `Chunk`) and materialize it as a `ColumnConst`, skipping the covered pages' reads and decode. + +## Tiers (both kept) + +| Tier | Source | Always present? | Exact flag? | Granularity | +|------|--------|-----------------|-------------|-------------| +| 1 (existing) | footer `ColumnMetaData.statistics` | yes | yes (`is_min_value_exact`) | whole chunk | +| 2 (this doc) | Column Index (per page) | no (optional) | no | per subgroup | + +Tier 1 stays the always-on baseline and the **only** safe detector for `BYTE_ARRAY` / +`FIXED_LEN_BYTE_ARRAY` (Column Index has no per-page exactness flag; 16-byte truncation can make two +distinct strings compare equal). Tier 2 is opportunistic: only for fixed-width numeric/date/time, +only when the Column Index is already loaded, only for chunks tier 1 did not already mark constant. + +## Key decision: do NOT change subgroup sizing + +Aligning subgroups to page boundaries would fragment the block stream into many tiny chunks +(pages are far smaller than a row group), and a subgroup carries all columns so its size is bounded +by the non-constant columns anyway. Instead, keep subgroup boundaries exactly as today and do +**per-subgroup, per-column** detection: a column is constant for a subgroup iff every Column-Index +page overlapping the subgroup's row range is constant with the *same* value (or every such page is +`null_pages`). Chunk count is unchanged; we just catch subgroups that sit inside a constant run. + +## Phases + +- **Phase 0** — retain per-page constant info. `applyColumnIndex` currently discards the parsed + `parq::ColumnIndex`. Keep a compact per-page summary on `ColumnChunk` (value + `is_const` + + `all_null`), plus the page→`first_row_index` map already in the Offset Index. Populate only for + eligible types. +- **Phase 1** — `detectConstantSubchunk(column, column_info, [start_row, end_row))`: scan the pages + overlapping the range; return constant + value when all are `is_const` and share one value; + all-null when all are `null_pages`. +- **Phase 2** — call it in `intersectColumnIndexResultsAndInitSubgroups` for each subgroup / + primitive column that tier 1 didn't already mark constant; set `subchunk.is_constant` / + `is_all_null` / `constant_value` (the same fields `decodePrimitiveColumn` propagates). + `formOutputColumn` needs no change (already emits `ColumnConst`). +- **Phase 3** — skip work for constant subchunks: `decodePrimitiveColumn` skips decode on + `subchunk.is_constant`; `determinePagesToPrefetch` skips fetching a page only when it is constant + in **every** subgroup that overlaps it. +- **Phase 4** — stateless tests (page-run constant, all-null-per-page, byte-array negative/truncation + guard, `GROUP BY` correctness), with a new `ParquetConstantColumnSubchunks` ProfileEvent to prove + tier 2 fired. +- **Phase 5** — ProfileEvents comparison on clustered data: expect further `S3GetObject` / + `ParquetFetchWaitTimeMicroseconds` drops with chunk count unchanged. + +## Optional force-load + +By default tier 2 only uses the Column Index when it is already loaded (columns with a predicate +push-down). `input_format_parquet_use_column_index_for_constant_columns` (default off) extends it: +the Column Index (+ Offset Index) is force-loaded for eligible read columns that have no predicate, +so tier 2 can also fire on them. Cost is a small extra read of the (tiny, tail-contiguous, coalesced) +index; worthwhile mainly for sorted / low-cardinality columns. `applyColumnIndex` records per-page +constant info but skips predicate pruning when the column has no condition. A future `auto` mode +could gate this on footer signals (row-group `sorting_columns`, low compressed-bytes-per-value, +dictionary encoding stats) instead of an all-or-nothing switch. + +## Cast safety (future-proofing) + +The optimization only fires when the stats decoder needs no value-transforming conversion +(`SchemaConverter` sets `allow_stats` accordingly), so today `input_type == output_type` for every +constant column and no cast is applied. To keep the constant path correct if `allow_stats` is ever +generalized to allow transforming casts, `formOutputColumn` builds the single-value constant in +`input_type` and runs the same `castColumn` the per-row decode uses when `needs_cast` is set - a +no-op today, O(1) on the `ColumnConst`, and it preserves const-ness. The all-null constant is +synthesized directly in the output domain (Null / output default), so it is not cast. The mixed fill +already goes through the normal `formOutputColumn` cast, so it is future-safe too. This does not +touch the `allow_stats` decision itself. + +## Guardrails + +- All types, including `BYTE_ARRAY` / `FIXED_LEN_BYTE_ARRAY` strings. No truncation guard is needed + for the `min == max` case: statistics/Column-Index bounds are always valid + (`min <= every value <= max`) and truncation only widens them, so `min == max` proves a single + exact value (a truncated or multi-valued page yields `min < max`). This holds at both the chunk + level (tier 1) and per page (tier 2), so neither needs the `is_*_value_exact` flag. +- Gate on the existing `input_format_parquet_use_constant_column_optimization` setting; the + force-load above is additionally gated by + `input_format_parquet_use_column_index_for_constant_columns`. +- Not applied when `input_format_parquet_verify_checksums` is enabled (its default). A constant + chunk or subchunk is materialized without reading its data pages, so their page checksums would + never be verified. With verification requested, such chunks are decoded normally, and the + optimization applies only when verification is turned off. +- Partial-page subgroup boundaries are fine: a partial overlap of a constant page still yields that + value, as long as every overlapping page is constant with the shared value. + +## Mixed-topology fill (Approach B) — implemented, default off + +`input_format_parquet_fill_constant_pages` handles constant runs *shorter* than / straddling a +subgroup: `fillConstantPagesAndDecodeRest` fills single-value pages from the Column Index and decodes +only the varying ones, and `determinePagesToPrefetch` skips prefetching the filled pages (a page +shared with a subgroup that decodes it normally is still fetched — `willFillConstantPages` is +deterministic so both paths agree). The fill walks the rows that pass the filter (`row_subgroup.filter`), so it works under PREWHERE / +row-level filters and page-pruning predicates too - it produces exactly `rows_pass` values for any +filter, and because the decision no longer depends on `rows_pass` it is identical at prefetch time +and decode time (so the prefetch-skip can never drop a page the decode needs). All-null pages are +filled (nulls via the compact values + null map + `expand` path, or the output default under +`null_as_default`); a subgroup with an all-null page falls back only when the output can represent +neither null nor a default. The one remaining gate is `needs_cast`: the fill writes the Column Index +value into the `decoded_type` column, valid only when no post-decode cast applies (resolving whether +`decodeField` yields the decoded or the output value domain is build-gated). Experimental, off by +default; needs a build + correctness tests before it can be trusted. diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index c9b79615610b7..d4bd1e9e71482 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1847,6 +1847,8 @@ The server successfully detected this situation and will download merged part fr M(ParquetPrunedRowGroups, "The total number of row groups pruned from parquet data", ValueType::Number) \ M(ParquetReadPages, "The total number of Parquet data pages read", ValueType::Number) \ M(ParquetPrunedPages, "The total number of pages pruned from parquet data via column index", ValueType::Number) \ + M(ParquetConstantColumnChunks, "The total number of parquet column chunks materialized from a single value in their min/max statistics, without reading their data pages", ValueType::Number) \ + M(ParquetConstantColumnSubchunks, "The total number of parquet column subchunks (per row subgroup) materialized from a single value in their per-page column-index statistics, without decoding their data pages", ValueType::Number) \ M(ParquetDecodingTasks, "Tasks issued by parquet reader", ValueType::Number) \ M(ParquetDecodingTaskBatches, "Task groups sent to a thread pool by parquet reader", ValueType::Number) \ M(ParquetPrefetcherReadRandomRead, "The total number of reads with ReadMode::RandomRead by DB::Parquet::Prefetcher", ValueType::Number) \ diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 4951eda47549b..c727ed8cd3d1b 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -235,6 +235,15 @@ When reading GeoParquet files, skip whole row groups and, together with `input_f )", 0) \ DECLARE(Bool, input_format_parquet_use_offset_index, true, R"( Minor tweak to how pages are read from parquet file when no page filtering is used. +)", 0) \ + DECLARE(Bool, input_format_parquet_use_constant_column_optimization, true, R"( +When a Parquet column chunk provably holds a single value in every row (according to its min/max statistics), materialize that value directly instead of reading and decoding the column's data pages. Not applied when `input_format_parquet_verify_checksums` is enabled, because the data pages of such chunks are not read and their checksums would not be verified. +)", 0) \ + DECLARE(Bool, input_format_parquet_use_column_index_for_constant_columns, false, R"( +Load the Parquet Column Index for read columns that have no predicate of their own, so the constant-column optimization can also skip data pages that are single-valued over a row subgroup (not just over a whole column chunk). Costs a small extra read of the (tiny) Column Index; only worthwhile when columns are sorted or low-cardinality. Applies only when `input_format_parquet_use_constant_column_optimization` is enabled. +)", 0) \ + DECLARE(Bool, input_format_parquet_fill_constant_pages, false, R"( +Experimental. When a Parquet column is single-valued over some data pages but not the whole row subgroup, fill those pages' rows from the per-page Column Index statistics instead of reading and decoding them (mixed-topology subgroups). Extends the constant-column optimization below the subgroup granularity. Requires `input_format_parquet_use_constant_column_optimization`; disabled by default. )", 0) \ DECLARE(Bool, input_format_parquet_verify_checksums, true, R"( Verify page checksums when reading parquet files. diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index f93c54df707b1..4e8a438f8efc6 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -54,6 +54,9 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() { {"export_merge_tree_part_check_destination_schema_staleness_ms", 0, 5000, "New setting: how stale the latest Iceberg destination metadata version may be when each part export task checks that the destination schema and partition spec did not change since the export was scheduled."}, {"export_merge_tree_part_allow_lossy_cast", false, false, "The setting is obsolete. `EXPORT PART` and `EXPORT PARTITION` cast values the way `INSERT ... SELECT` does."}, + {"input_format_parquet_use_constant_column_optimization", false, true, "New setting: when a Parquet column chunk provably holds a single value in every row (per its min/max statistics), materialize that value directly instead of reading and decoding the column's data pages."}, + {"input_format_parquet_use_column_index_for_constant_columns", false, false, "New setting: load the Parquet Column Index for read columns without a predicate so the constant-column optimization can also skip data pages that are single-valued over a row subgroup."}, + {"input_format_parquet_fill_constant_pages", false, false, "New experimental setting: when a Parquet column is single-valued over some data pages of a row subgroup, fill those pages from the Column Index statistics instead of reading and decoding them."}, }); addSettingsChanges(settings_changes_history, "26.8.35.20001.altinityantalya", { diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index c169db9af1df1..c50ad8ddf175a 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -231,6 +231,9 @@ FormatSettings getFormatSettings(const ContextPtr & context, const Settings & se format_settings.parquet.page_filter_push_down = settings[Setting::input_format_parquet_page_filter_push_down]; format_settings.parquet.spatial_filter_push_down = settings[Setting::input_format_parquet_spatial_filter_push_down]; format_settings.parquet.use_offset_index = settings[Setting::input_format_parquet_use_offset_index]; + format_settings.parquet.use_constant_column_optimization = settings[Setting::input_format_parquet_use_constant_column_optimization]; + format_settings.parquet.use_column_index_for_constant_columns = settings[Setting::input_format_parquet_use_column_index_for_constant_columns]; + format_settings.parquet.fill_constant_pages = settings[Setting::input_format_parquet_fill_constant_pages]; format_settings.parquet.enable_json_parsing = settings[Setting::input_format_parquet_enable_json_parsing]; format_settings.parquet.memory_low_watermark = settings[Setting::input_format_parquet_memory_low_watermark]; diff --git a/src/Formats/FormatSettings.h b/src/Formats/FormatSettings.h index 315bf7ab8cf05..ab7d11ca09a91 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -386,6 +386,9 @@ struct FormatSettings size_t footer_read_size = 0; bool page_filter_push_down = true; bool use_offset_index = true; + bool use_constant_column_optimization = true; + bool use_column_index_for_constant_columns = false; + bool fill_constant_pages = false; bool enable_json_parsing = true; bool preserve_order = false; diff --git a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp index b85c225850081..d15cd422a7694 100644 --- a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp +++ b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp @@ -772,7 +772,7 @@ void ReadManager::scheduleTask(Task task, bool is_first_in_group, MemoryUsageDif /// Queue this subgroup's data-page reads; startPrefetch (below) issues them and charges /// compressed bytes to the ColumnDataPrefetch budget, separate from the decode budget, /// so many row groups prefetch ahead while only a few decode at once. - reader.determinePagesToPrefetch(column, row_subgroup, row_group, prefetches); + reader.determinePagesToPrefetch(column, row_subgroup.columns.at(task.column_idx), reader.primitive_columns.at(task.column_idx), row_subgroup, row_group, prefetches); /// Side note: would be nice to avoid reading the dictionary if all dictionary-encoded /// pages were filtered out (e.g. if it's a 100 MB column chunk with unique long strings, diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 4fe93f9570533..fdf5dcc142717 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -55,6 +56,8 @@ namespace ProfileEvents extern const Event ParquetColumnsFilterExpression; extern const Event ParquetReadPages; extern const Event ParquetPrunedPages; + extern const Event ParquetConstantColumnChunks; + extern const Event ParquetConstantColumnSubchunks; } namespace DB::Parquet @@ -862,6 +865,8 @@ void Reader::prefilterAndInitRowGroups(const std::optionalmeta_data.statistics.__isset.null_count && column.meta->meta_data.statistics.null_count == 0; column.need_null_map = is_nullable && !null_count_is_known_to_be_zero; + + detectConstantColumn(column, primitive_columns[column_idx]); } } @@ -1071,7 +1076,9 @@ void Reader::initializePrefetches() /// Dictionary page. size_t dict_page_length = 0; - if (column.meta->meta_data.__isset.dictionary_page_offset) + /// A constant column chunk is materialized without reading any pages (data or + /// dictionary), so don't prefetch its dictionary page either. + if (column.meta->meta_data.__isset.dictionary_page_offset && !column.is_constant) { /// We assume that the dictionary page is immediately followed by the first data page. size_t start = size_t(column.meta->meta_data.dictionary_page_offset); @@ -1149,8 +1156,23 @@ void Reader::initializePrefetches() max_header_length, /*likely_to_be_used=*/ true); } + /// A constant column chunk is materialized without reading any of its pages (see + /// detectConstantColumn and decodePrimitiveColumn), so it needs neither the offset index + /// nor the column index nor the data pages. The row group already passed the key + /// condition via its min == max hyperrectangle, so page-level pruning is redundant here. + + /// Force-load the column index (per-page stats) for an eligible column even without a + /// predicate on it, so tier-2 constant detection (detectConstantSubchunk) can run. Gated + /// by input_format_parquet_use_column_index_for_constant_columns. Requires the offset + /// index too (page -> row mapping), loaded just below. + const bool force_column_index_for_const = + options.format.parquet.use_column_index_for_constant_columns + && !column.is_constant + && constColumnMaterializationEligible(primitive_columns[column_idx]) + && column.meta->__isset.column_index_offset && column.meta->__isset.column_index_length; + /// Offset index. - if (use_offset_index && + if ((use_offset_index || force_column_index_for_const) && !column.is_constant && column.meta->__isset.offset_index_offset && column.meta->__isset.offset_index_length) { column.offset_index_prefetch = prefetcher.registerRange( @@ -1159,7 +1181,8 @@ void Reader::initializePrefetches() } /// Column index. - column.use_column_index = !primitive_columns[column_idx].column_index_conditions.empty() + column.use_column_index = !column.is_constant + && (!primitive_columns[column_idx].column_index_conditions.empty() || force_column_index_for_const) && column.offset_index_prefetch && column.meta->__isset.column_index_offset && column.meta->__isset.column_index_length; if (column.use_column_index) @@ -1179,10 +1202,11 @@ void Reader::initializePrefetches() if (file_metadata.created_by == "parquet-mr" && !column.meta->meta_data.__isset.dictionary_page_offset && !column.meta->__isset.offset_index_offset) data_pages_extra_bytes = std::min(100ul, prefetcher.getFileSize() - size_t(column.meta->meta_data.data_page_offset) - column.data_pages_bytes); - column.data_pages_prefetch = prefetcher.registerRange( - size_t(column.meta->meta_data.data_page_offset), - column.data_pages_bytes + data_pages_extra_bytes, - /*likely_to_be_used=*/ true); + if (!column.is_constant) + column.data_pages_prefetch = prefetcher.registerRange( + size_t(column.meta->meta_data.data_page_offset), + column.data_pages_bytes + data_pages_extra_bytes, + /*likely_to_be_used=*/ true); } } @@ -2014,7 +2038,9 @@ void Reader::applyColumnIndex(ColumnChunk & column, const PrimitiveColumnInfo & try { chassert(column.use_column_index); - chassert(!column_info.column_index_conditions.empty()); + /// column_index_conditions may be empty when the column index was force-loaded only for tier-2 + /// constant detection (input_format_parquet_use_column_index_for_constant_columns); in that + /// case we record per-page constant info below but do no page-level predicate pruning. auto data = prefetcher.getRangeData(column.column_index_prefetch); parq::ColumnIndex column_index; @@ -2032,6 +2058,17 @@ void Reader::applyColumnIndex(ColumnChunk & column, const PrimitiveColumnInfo & /// against, which may differ from decoded_type - see cast_stats_to_output_type. const IDataType & output_block_type = *extended_sample_block_data_types.at(column_info.idx_in_output_block); + /// Tier 2 constant-column detection: retain per-page constant info from the Column Index for + /// use by detectConstantSubchunk. Only when eligible and the whole chunk is not already + /// constant (tier 1). No truncation guard is needed even though the Column Index has no + /// per-page exactness flag: bounds are always valid (min_value <= every value <= max_value) + /// and truncation only widens them, so a per-page min_value == max_value proves a single exact + /// value - for BYTE_ARRAY strings too (a truncated value would give min_value < max_value). + const bool record_page_const = + constColumnMaterializationEligible(column_info) && !column.is_constant; + if (record_page_const) + column.page_const_info.assign(num_pages, ColumnChunk::PageConstInfo{}); + Hyperrectangle hyperrectangle(extended_sample_block.columns(), Range::createWholeUniverse()); size_t prev_row_idx = 0; // start of the latest range of rows that pass filter size_t pruned_pages = 0; @@ -2041,7 +2078,15 @@ void Reader::applyColumnIndex(ColumnChunk & column, const PrimitiveColumnInfo & range = Range::createWholeUniverse(); bool always_null = !column_index.null_pages.empty() && column_index.null_pages[page_idx]; - bool can_be_null = !column_index.__isset.null_counts || column_index.null_counts[page_idx] != 0; + /// A required column (max def level 0) can never contain nulls, regardless of whether the + /// Column Index carries null_counts. This matters for tier-2 constant detection below: + /// ClickHouse's own writer only emits null_counts for nullable columns (see Write.cpp, + /// has_null_count = max_def == 1), so without the `nullable` guard can_be_null would be + /// spuriously true for every required column and the is_const branch would never fire. + bool can_be_null = nullable && (!column_index.__isset.null_counts || column_index.null_counts[page_idx] != 0); + + if (record_page_const) + column.page_const_info[page_idx].all_null = always_null; if (nullable && always_null) { @@ -2056,6 +2101,16 @@ void Reader::applyColumnIndex(ColumnChunk & column, const PrimitiveColumnInfo & column_info.decoder.decodeField(column_index.min_values[page_idx], /*is_max=*/ false, *column_info.decoded_type, output_block_type, range.left); column_info.decoder.decodeField(column_index.max_values[page_idx], /*is_max=*/ true, *column_info.decoded_type, output_block_type, range.right); + /// A page with no nulls whose decoded min == max holds a single value (post-cast + /// output domain, like tier 1). Captured before adjustRangeFromIndexIfNeeded, which + /// mutates the range for null/default handling. + if (record_page_const && !can_be_null + && !range.left.isNull() && range.left == range.right) + { + column.page_const_info[page_idx].is_const = true; + column.page_const_info[page_idx].value = range.left; + } + /// Nullability is checked against each extracted condition below. A nullable /// ClickHouse output can therefore keep the finite range from the column index. adjustRangeFromIndexIfNeeded(range, column_info, can_be_null && !column_info.output_nullable); @@ -2307,6 +2362,34 @@ void Reader::intersectColumnIndexResultsAndInitSubgroups(RowGroup & row_group) } if (options.format.defaults_for_omitted_fields) row_subgroup.block_missing_values.init(sample_block->columns()); + + /// Tier 2 constant detection: for each primitive column not already whole-chunk-constant + /// (tier 1), check whether it is constant over this subgroup's row range using the + /// per-page Column Index info retained in applyColumnIndex. If so, mark the subchunk so + /// decodePrimitiveColumn skips decoding it and formOutputColumn materializes a ColumnConst. + /// The subgroup's pages are still skipped forward by the next subgroup's + /// skipToRowOrNextPage; skipping the prefetch itself is a separate follow-up. + if (row_group.need_to_process) + { + for (size_t i = 0; i < primitive_columns.size(); ++i) + { + ColumnChunk & column = row_group.columns[i]; + if (column.is_constant) + continue; // tier 1 already materializes the whole chunk + bool all_null = false; + Field value; + if (detectConstantSubchunk( + column, primitive_columns[i], substart, subend, + size_t(row_group.meta->num_rows), all_null, value)) + { + ColumnSubchunk & subchunk = row_subgroup.columns[i]; + subchunk.is_constant = true; + subchunk.is_all_null = all_null; + subchunk.constant_value = std::move(value); + ProfileEvents::increment(ProfileEvents::ParquetConstantColumnSubchunks); + } + } + } } } row_group.intersected_row_ranges_after_column_index = std::move(row_ranges); @@ -2345,12 +2428,20 @@ void Reader::decodeOffsetIndex(ColumnChunk & column, const RowGroup & row_group) } } -void Reader::determinePagesToPrefetch(ColumnChunk & column, const RowSubgroup & row_subgroup, const RowGroup & row_group, std::vector & out) +void Reader::determinePagesToPrefetch(ColumnChunk & column, const ColumnSubchunk & subchunk, const PrimitiveColumnInfo & column_info, const RowSubgroup & row_subgroup, const RowGroup & row_group, std::vector & out) { chassert(row_subgroup.filter.rows_pass > 0); + if (column.is_constant) + return; // constant column: data pages are never read if (column.offset_index.page_locations.empty()) return; // no offset index, can't prefetch individual pages + /// If this subgroup will fill its single-value pages from the Column Index instead of decoding + /// them (input_format_parquet_fill_constant_pages), don't prefetch those pages. Deterministic, so + /// the decode path (willFillConstantPages) makes the same decision. A const page shared with a + /// subgroup that decodes it normally is still claimed by that subgroup and thus fetched. + const bool fill_const_pages = willFillConstantPages(column, column_info, row_group, row_subgroup); + if (column.data_pages.empty()) { const auto & locations = column.offset_index.page_locations; @@ -2412,6 +2503,25 @@ void Reader::determinePagesToPrefetch(ColumnChunk & column, const RowSubgroup & if (passes_filter && row_subgroup.filter.rows_pass < row_subgroup.filter.rows_total) passes_filter = !memoryIsZero(row_subgroup.filter.filter.data(), start_row_idx - row_subgroup.start_row_idx, end_row_idx - row_subgroup.start_row_idx); + /// Tier 2: this subgroup's column is constant (detectConstantSubchunk), so it decodes nothing + /// and needs no pages. Treat every page as not-needed-by-this-subgroup; a page fully inside + /// this subgroup is then released below (never fetched), while a page shared with a + /// neighbouring non-constant subgroup is left for that subgroup to claim. Safe because a + /// constant subgroup never calls skipToRowOrNextPage, and non-constant subgroups jump + /// directly to their own (claimed) pages via the offset index. + if (subchunk.is_constant) + passes_filter = false; + + /// Mixed-topology fill: this subgroup fills its single-value pages instead of decoding them, + /// so it does not need those pages. (Varying pages in the same subgroup are still claimed.) + if (passes_filter && fill_const_pages) + { + const size_t gid = size_t(page.meta - column.offset_index.page_locations.data()); + if (gid < column.page_const_info.size() + && (column.page_const_info[gid].is_const || column.page_const_info[gid].all_null)) + passes_filter = false; + } + if (passes_filter) out.push_back(&page.prefetch); // this subgroup needs this page else if (page.end_row_idx > subgroup_end) @@ -2485,8 +2595,351 @@ double Reader::estimateColumnMemoryBytesPerRow(const ColumnChunk & column, const return res; } +bool Reader::constColumnMaterializationEligible(const PrimitiveColumnInfo & column_info) const +{ + if (!options.format.parquet.use_constant_column_optimization) + return false; + /// A constant chunk or subchunk is materialized from statistics without reading its data pages, + /// so their page checksums would never be verified. When verification is requested, decode normally. + if (options.format.parquet.verify_checksums) + return false; + /// We rely on min/max statistics being both present and decodable. + if (!column_info.decoder.allow_stats) + return false; + + /// Only flat, top-level primitive columns, so that one parquet value maps 1:1 to one output row + /// and formOutputColumn can materialize the value directly. Exclude: + /// - arrays (leaf repetition level > 0, or any array level: max_array_def > 0), + /// - physically-nullable structs read as Nullable(Tuple(...)) (group_nullable), + /// - leaves nested inside a Tuple/Map/Array output column (the output column is not primitive). + /// A plain Nullable(T) is fine: it adds a definition level but no repetition, and its output + /// column is still primitive; the no-nulls check below and the output_nullable wrap handle it. + if (column_info.levels.back().rep != 0 || column_info.max_array_def != 0 || column_info.group_nullable) + return false; + if (column_info.idx_in_output_block >= sample_block_to_output_columns_idx.size()) + return false; + const auto & output_idx = sample_block_to_output_columns_idx.at(column_info.idx_in_output_block); + if (!output_idx.has_value() || !output_columns[output_idx.value()].is_primitive) + return false; + /// A constant is materialized from its decoded (input) value. Without a post-decode cast, that + /// value is also the output value (the same invariant the Column Index path relies on, see + /// willFillConstantPages), so a column that needs a cast is read and decoded normally. + if (output_columns[output_idx.value()].needs_cast) + return false; + return true; +} + +void Reader::detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInfo & column_info) const +{ + if (!constColumnMaterializationEligible(column_info)) + return; + + const auto & meta_data = column.meta->meta_data; + if (!meta_data.__isset.statistics) + return; + const auto & stats = meta_data.statistics; + + bool physically_nullable = column_info.levels.back().def > 0; + + /// All-null chunk: every row is null (null_count == num_values). This is provable only for a + /// physically nullable leaf (a REQUIRED column can have no nulls), and only when the writer + /// emitted the null_count statistic. No value is decoded at all, so this skips the min/max + /// exactness and truncation concerns below. We materialize `Null` for a Nullable output, or the + /// output default when `null_as_default` substitutes nulls for a non-nullable output; a + /// non-nullable output without null substitution cannot represent the result, so we leave the + /// chunk to the normal decode path (which errors on the null). formOutputColumn records every + /// row in block_missing_values for this case. + if (physically_nullable && stats.__isset.null_count && stats.null_count == meta_data.num_values + && meta_data.num_values > 0) + { + const bool null_as_default = options.format.null_as_default && !column_info.output_nullable; + if (column_info.output_nullable) + column.constant_value = Null{}; + else if (null_as_default) + column.constant_value = column_info.output_type->getDefault(); + else + return; + + column.is_constant = true; + column.is_all_null = true; + ProfileEvents::increment(ProfileEvents::ParquetConstantColumnChunks); + return; + } + + /// All rows must be non-null. If the parquet column is physically nullable (max definition level + /// > 0), require the statistics to prove zero nulls. If it is REQUIRED (definition level 0) there + /// can be no nulls, so the null_count statistic - which writers commonly omit for non-nullable + /// columns - is unnecessary. A chunk that mixes the value with nulls has two distinct logical + /// values and still needs a null map. + if (physically_nullable && (!stats.__isset.null_count || stats.null_count != 0)) + return; + + if (!stats.__isset.min_value || !stats.__isset.max_value) + return; + if (stats.min_value != stats.max_value) + return; + + /// No truncation guard is needed for the min == max case, including BYTE_ARRAY / + /// FIXED_LEN_BYTE_ARRAY. Statistics bounds are always valid (min_value <= every value <= + /// max_value) and truncation only ever widens them, so a truncated value - or any chunk with two + /// distinct values - yields min_value < max_value. Hence min_value == max_value can only occur for + /// a single value short enough to be stored exactly, so `is_*_value_exact` is implied. + + Field value; + /// Decoded (input) domain, which is the output domain because no cast is applied (see above). + column_info.decoder.decodeField(stats.min_value, /*is_max=*/ false, *column_info.decoded_type, *column_info.decoded_type, value); + /// decodeField leaves `value` unchanged (Null) if the physical type is unsupported for stats. + if (value.isNull()) + return; + + column.is_constant = true; + column.constant_value = std::move(value); + ProfileEvents::increment(ProfileEvents::ParquetConstantColumnChunks); +} + +bool Reader::detectConstantSubchunk( + const ColumnChunk & column, const PrimitiveColumnInfo & column_info, + size_t start_row, size_t end_row, size_t row_group_num_rows, + bool & out_all_null, Field & out_value) const +{ + if (column.page_const_info.empty()) + return false; + const size_t num_pages = column.offset_index.page_locations.size(); + if (num_pages == 0 || column.page_const_info.size() != num_pages) + return false; + + bool any = false; + bool all_pages_null = true; + bool all_pages_const_same = true; + Field value; + bool value_set = false; + + for (size_t p = 0; p < num_pages; ++p) + { + const size_t p_start = static_cast(column.offset_index.page_locations[p].first_row_index); + const size_t p_end = (p + 1 < num_pages) + ? static_cast(column.offset_index.page_locations[p + 1].first_row_index) + : row_group_num_rows; + if (p_end <= start_row || p_start >= end_row) + continue; // page does not overlap the subgroup's row range + + any = true; + const auto & pci = column.page_const_info[p]; + if (!pci.all_null) + all_pages_null = false; + if (pci.is_const) + { + if (!value_set) + { + value = pci.value; + value_set = true; + } + else if (value != pci.value) + all_pages_const_same = false; + } + else + { + all_pages_const_same = false; + } + } + + if (!any) + return false; + + if (all_pages_null) + { + /// Every overlapping page is entirely null - mirror detectConstantColumn's all-null branch. + const bool null_as_default = options.format.null_as_default && !column_info.output_nullable; + if (column_info.output_nullable) + out_value = Null{}; + else if (null_as_default) + out_value = column_info.output_type->getDefault(); + else + return false; // non-nullable output without null substitution: let normal decode error + out_all_null = true; + return true; + } + + if (all_pages_const_same && value_set) + { + out_all_null = false; + out_value = value; + return true; + } + + return false; +} + +bool Reader::willFillConstantPages( + const ColumnChunk & column, const PrimitiveColumnInfo & column_info, + const RowGroup & row_group, const RowSubgroup & row_subgroup) const +{ + if (!options.format.parquet.fill_constant_pages) + return false; + if (column.is_constant) + return false; // whole chunk already constant (tier 1) + if (column.page_const_info.empty()) + return false; // no Column Index info retained + /// PREWHERE / row-level filters and page-pruning predicates are all handled: the fill walks only + /// the rows that pass the filter (row_subgroup.filter), so it produces exactly rows_pass values + /// for any filter, and pruned pages fall outside the subgroup's surviving ranges. The decision + /// here is independent of rows_pass, so it is identical at prefetch time and decode time. + if (!constColumnMaterializationEligible(column_info)) + return false; + + /// We fill the decoded_type column with the output-domain value from the Column Index, which is + /// only valid when no post-decode cast is applied (decoded_type == output value type). + const auto & output_idx = sample_block_to_output_columns_idx.at(column_info.idx_in_output_block); + if (!output_idx.has_value() || output_columns[output_idx.value()].needs_cast) + return false; + + const auto & pages = column.offset_index.page_locations; + const size_t num_pages = pages.size(); + if (num_pages == 0 || column.page_const_info.size() != num_pages) + return false; + + /// Require at least one fillable page (single-value or all-null) overlapping the subgroup. An + /// all-null page is only representable when the output is Nullable or null_as_default substitutes + /// a default; otherwise fall back to the standard decode (which raises the usual not-null error). + const bool null_as_default = options.format.null_as_default && !column_info.output_nullable; + const bool nulls_representable = column_info.output_nullable || null_as_default; + const size_t start = row_subgroup.start_row_idx; + const size_t end = start + row_subgroup.filter.rows_total; + const size_t rg_rows = size_t(row_group.meta->num_rows); + bool any_fillable = false; + for (size_t p = 0; p < num_pages; ++p) + { + const size_t p_start = size_t(pages[p].first_row_index); + const size_t p_end = (p + 1 < num_pages) ? size_t(pages[p + 1].first_row_index) : rg_rows; + if (p_end <= start || p_start >= end) + continue; + const auto & pci = column.page_const_info[p]; + if (pci.all_null && !nulls_representable) + return false; + if (pci.is_const || pci.all_null) + any_fillable = true; + } + return any_fillable; +} + +void Reader::fillConstantPagesAndDecodeRest( + ColumnChunk & column, const PrimitiveColumnInfo & column_info, + ColumnSubchunk & subchunk, const RowGroup & row_group, RowSubgroup & row_subgroup) +{ + const size_t start = row_subgroup.start_row_idx; + const size_t rows_total = row_subgroup.filter.rows_total; + const auto & pages = column.offset_index.page_locations; + const size_t num_pages = pages.size(); + const size_t rg_rows = size_t(row_group.meta->num_rows); + const auto & filter = row_subgroup.filter.filter; + + ColumnUInt8::Container * null_map_data = subchunk.null_map + ? &assert_cast(*subchunk.null_map).getData() + : nullptr; + + auto page_end_of = [&](size_t pg) { return (pg + 1 < num_pages) ? size_t(pages[pg + 1].first_row_index) : rg_rows; }; + + /// Iterate the ranges of rows that pass the filter (like the standard row-range decode), and walk + /// the pages overlapping each range. Within a passing range every row is output, so a constant / + /// all-null page contributes exactly its overlapping row count, and a varying page is decoded for + /// that contiguous sub-range. This produces the compact (non-null) values + null map that the + /// caller's expand() / Nullable-wrap / null_as_default tail finalizes - matching the normal + /// decode for any rows_pass, so no rows_pass == rows_total restriction is needed. + size_t page_cursor = 0; // forward cursor over page_locations + size_t row_subidx = 0; // offset within [0, rows_total) + while (true) + { + size_t num_rows = rows_total - row_subidx; + if (!filter.empty()) + { + while (row_subidx < rows_total && !filter[row_subidx]) + ++row_subidx; + num_rows = 0; + while (row_subidx + num_rows < rows_total && filter[row_subidx + num_rows]) + ++num_rows; + } + if (!num_rows) + break; + const size_t range_start = start + row_subidx; + const size_t range_end = range_start + num_rows; + row_subidx += num_rows; + + size_t row = range_start; + while (row < range_end) + { + while (page_cursor < num_pages && page_end_of(page_cursor) <= row) + ++page_cursor; + chassert(page_cursor < num_pages); + const size_t seg_end = std::min(range_end, page_end_of(page_cursor)); + chassert(seg_end > row); + const size_t count = seg_end - row; + const auto & pci = column.page_const_info[page_cursor]; + + if (pci.is_const) + { + /// Fill the single value without reading the page (value is in decoded_type domain, + /// which equals the output value domain - willFillConstantPages required no cast). A + /// single-value page has no nulls, so any null map gets zeros for these rows. + subchunk.column->insertMany(pci.value, count); + if (null_map_data) + null_map_data->resize_fill(null_map_data->size() + count, 0); + } + else if (pci.all_null) + { + /// All-null page: no non-null values; mark these rows null (expand() fills defaults + /// later). null_map exists here (an all-null page implies need_null_map). + chassert(null_map_data); + null_map_data->resize_fill(null_map_data->size() + count, 1); + } + else + { + /// Varying page: decode the contiguous passing sub-range [row, seg_end). All rows in + /// it pass, so no per-row filter is applied here. skipToRowOrNextPage jumps to the page + /// via the offset index, stepping over filled const/all-null pages without loading them. + skipToRowOrNextPage(row, column, column_info); + readRowsInPage(seg_end, subchunk, column, column_info, /*row_subgroup=*/ nullptr); + } + + row = seg_end; + } + } +} + void Reader::decodePrimitiveColumn(ColumnChunk & column, const PrimitiveColumnInfo & column_info, ColumnSubchunk & subchunk, const RowGroup & row_group, RowSubgroup & row_subgroup, MemoryUsageDiff & diff) { + /// subchunk.is_constant is set either here from column.is_constant (tier 1, whole chunk) or + /// during subgroup init by detectConstantSubchunk (tier 2, this row subgroup). Either way we skip + /// decoding and let formOutputColumn materialize the value as a ColumnConst. + if (column.is_constant && !subchunk.is_constant) + { + subchunk.is_constant = true; + subchunk.constant_value = column.constant_value; + subchunk.is_all_null = column.is_all_null; + } + + if (subchunk.is_constant) + { + /// This subchunk provably holds a single value in every row - either the whole chunk (tier 1, + /// detectConstantColumn; its data pages were never fetched) or just this subgroup's row range + /// (tier 2, detectConstantSubchunk; the pages are skipped forward by the next subgroup's + /// skipToRowOrNextPage). Skip decoding and hand the value to formOutputColumn, which + /// materializes it directly in the final output type. The value is in the output (post-cast) + /// domain, so it must not go through the decoded_type column and castColumn path. We still run + /// the per-output-column bookkeeping below so the output column is formed once the last of its + /// primitive columns is done. (The subchunk fields were set above for tier 1, or during + /// subgroup init for tier 2.) + OutputColumnState & state = row_subgroup.output.at(column_info.idx_in_output_block); + chassert(!state.column); + size_t prev_count = state.primitive_columns_remaining.fetch_sub(1); + chassert(prev_count > 0); + if (prev_count == 1) + { + const auto & output_idx = sample_block_to_output_columns_idx.at(column_info.idx_in_output_block); + state.column = formOutputColumn(row_subgroup, output_idx.value(), row_subgroup.filter.rows_pass); + } + return; + } + /// Allocate columns for values, null map, and array offsets. size_t output_num_values_estimate = 0; @@ -2521,6 +2974,16 @@ void Reader::decodePrimitiveColumn(ColumnChunk & column, const PrimitiveColumnIn string_column->getChars().reserve(bytes_to_reserve); } + /// Mixed-topology fill (input_format_parquet_fill_constant_pages): when only part of this + /// subgroup is single-valued, fill the constant pages from the Column Index and decode only the + /// varying ones. Produces a full decoded_type column, so it replaces the decode loop below. + bool filled_constant_pages = false; + if (willFillConstantPages(column, column_info, row_group, row_subgroup)) + { + fillConstantPagesAndDecodeRest(column, column_info, subchunk, row_group, row_subgroup); + filled_constant_pages = true; + } + /// Find ranges of rows that pass filter and decode them. /// When we have per-page prefetches (offset index), some pages may have had their prefetch @@ -2544,7 +3007,11 @@ void Reader::decodePrimitiveColumn(ColumnChunk & column, const PrimitiveColumnIn !column.need_null_map; const size_t subgroup_end_row_idx = row_subgroup.start_row_idx + row_subgroup.filter.rows_total; - if (use_filter_in_decoder) + if (filled_constant_pages) + { + /// Already produced the whole subchunk column above; skip the normal decode loop. + } + else if (use_filter_in_decoder) { skipToRowOrNextPage(row_subgroup.start_row_idx, column, column_info); @@ -3363,6 +3830,48 @@ MutableColumnPtr Reader::formOutputColumn(RowSubgroup & row_subgroup, size_t out chassert(output_info.primitive_start + 1 == output_info.primitive_end); size_t primitive_idx = output_info.primitive_start; ColumnSubchunk & subchunk = row_subgroup.columns.at(primitive_idx); + + if (subchunk.is_constant) + { + /// Constant column chunk (see detectConstantColumn): the whole chunk is a single value, + /// so materialize it as a ColumnConst rather than an expanded column. This is O(1) instead + /// of O(rows), and the const-ness propagates downstream: a PREWHERE/WHERE predicate + /// computes its result from the value without expanding the stored column, and GROUP BY / + /// aggregation over this column get a const key. + ColumnPtr result; + if (subchunk.is_all_null) + { + /// constant_value was synthesized directly in the output domain (Null for a Nullable + /// output, or the output default under null_as_default), so no cast applies. + MutableColumnPtr single_value = output_info.output_type->createColumn(); + single_value->insert(subchunk.constant_value); + result = ColumnConst::create(std::move(single_value), num_rows); + + /// An all-null chunk must record every row in block_missing_values, matching the + /// normal decode path (which records nulls from the null map); needed for + /// input_format_null_as_default. + if (output_info.idx_in_output_block.has_value() + && *output_info.idx_in_output_block < row_subgroup.block_missing_values.getNumColumns()) + row_subgroup.block_missing_values.setBits(*output_info.idx_in_output_block, num_rows); + } + else + { + /// The value came from decodeField, i.e. the decoded/input domain. Build the const in + /// input_type and apply the same castColumn the per-row decode uses when the output + /// type differs. Today the optimization only fires when the stats decoder does not + /// need a value-transforming conversion (input_type == output_type), so this cast is a + /// no-op; it is here so the constant path stays correct if that ever changes. Casting a + /// ColumnConst is O(1) (one value) and preserves const-ness. + MutableColumnPtr single_value = output_info.input_type->createColumn(); + single_value->insert(subchunk.constant_value); + result = ColumnConst::create(std::move(single_value), num_rows); + if (output_info.needs_cast) + result = castColumn({result, output_info.input_type, output_info.name}, output_info.output_type); + } + + return IColumn::mutate(std::move(result)); + } + res = std::move(subchunk.column); if (output_info.idx_in_output_block.has_value() && diff --git a/src/Processors/Formats/Impl/Parquet/Reader.h b/src/Processors/Formats/Impl/Parquet/Reader.h index 63ffd2ffb07bf..6325e3d8acd01 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.h +++ b/src/Processors/Formats/Impl/Parquet/Reader.h @@ -338,6 +338,31 @@ struct Reader bool use_column_index = false; bool need_null_map = false; + /// This column chunk provably holds a single repeated value in every row (see + /// detectConstantColumn). When set, we skip prefetching and decoding the data pages and + /// materialize `constant_value` directly instead. `constant_value` is the already-decoded + /// value (not the raw parquet-encoded bytes). + bool is_constant = false; + Field constant_value; + /// Sub-case of `is_constant`: the chunk is provably all-null (null_count == num_values). + /// `constant_value` is then `Null` for a Nullable output, or the output default when + /// `null_as_default` substitutes nulls for a non-nullable output. formOutputColumn also + /// records every row in block_missing_values (the plain constant case has no nulls). + bool is_all_null = false; + + /// Per-page constant info from the Column Index (tier 2; see applyColumnIndex and + /// detectConstantSubchunk). Populated only when the column index is loaded, indexed by data + /// page. `value` is in the output (post-cast) domain. Empty when unavailable. For truncatable + /// physical types (BYTE_ARRAY / FIXED_LEN_BYTE_ARRAY) only `all_null` is trusted, never + /// `is_const` (the Column Index has no per-page exactness flag). + struct PageConstInfo + { + bool is_const = false; /// page holds a single non-null value + bool all_null = false; /// page is entirely null + Field value; /// the value when is_const + }; + std::vector page_const_info; + /// Prefetches. /// TODO [parquet]: Check that all handles and tokens are reset after correct stages. PrefetchHandle bloom_filter_header_prefetch; @@ -400,6 +425,15 @@ struct Reader /// Primitive column. MutableColumnPtr column; + /// Set by decodePrimitiveColumn when the source column chunk is constant (see + /// ColumnChunk::is_constant): `column` is then left empty and formOutputColumn materializes + /// `constant_value` directly in the final output type. `constant_value` is in the output + /// (post-cast) domain. + bool is_constant = false; + Field constant_value; + /// Mirror of ColumnChunk::is_all_null (see there). + bool is_all_null = false; + MutableColumnPtr null_map; /// For a leaf of a physically-nullable struct read as Nullable(Tuple(...)) (see @@ -610,13 +644,45 @@ struct Reader /// Call after prewhere is done on row subgroup. Un-requests prefetch for fully filtered out pages, /// adds pages that need prefetch to `out`. Must be called in order. /// May assign dictionary_page_prefetch. - void determinePagesToPrefetch(ColumnChunk & column, const RowSubgroup & row_subgroup, const RowGroup & row_group, std::vector & out); + void determinePagesToPrefetch(ColumnChunk & column, const ColumnSubchunk & subchunk, const PrimitiveColumnInfo & column_info, const RowSubgroup & row_subgroup, const RowGroup & row_group, std::vector & out); /// Guess how much memory ColumnSubchunk::{column, arrays_offsets} will use, per row. double estimateColumnMemoryBytesPerRow(const ColumnChunk & column, const RowGroup & row_group, const PrimitiveColumnInfo & column_info) const; void decodePrimitiveColumn(ColumnChunk & column, const PrimitiveColumnInfo & column_info, ColumnSubchunk & subchunk, const RowGroup & row_group, RowSubgroup & row_subgroup, MemoryUsageDiff & diff); + /// If the column chunk provably holds one repeated value in every row, sets column.is_constant + /// and column.constant_value. Two sub-cases, both from column chunk statistics (Tier 1): + /// - a single non-null value in every row (min_value == max_value, no nulls), or + /// - an all-null chunk (null_count == num_values), which also sets column.is_all_null. + /// Only applies to flat, top-level primitive columns; see the implementation for the exact + /// conditions. + void detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInfo & column_info) const; + + /// Shared eligibility gate for constant-column materialization (both tiers): the setting is on, + /// stats are decodable, and the leaf is a flat top-level primitive output column. + bool constColumnMaterializationEligible(const PrimitiveColumnInfo & column_info) const; + + /// Tier 2 (per row subgroup): using the retained per-page Column Index info + /// (ColumnChunk::page_const_info), decide whether `column` is constant over the row range + /// [start_row, end_row) covered by a subgroup. Returns true and sets out_all_null / out_value + /// when every overlapping page is all-null, or every overlapping page holds the same single + /// value. row_group_num_rows is the row group's total row count (for the last page's end). + bool detectConstantSubchunk( + const ColumnChunk & column, const PrimitiveColumnInfo & column_info, + size_t start_row, size_t end_row, size_t row_group_num_rows, + bool & out_all_null, Field & out_value) const; + + /// Mixed-topology fill (input_format_parquet_fill_constant_pages): true when this subgroup has + /// some single-value pages (and no all-null pages) that can be filled from the Column Index + /// while the rest is decoded normally. See willFillConstantPages / fillConstantPagesAndDecodeRest. + bool willFillConstantPages( + const ColumnChunk & column, const PrimitiveColumnInfo & column_info, + const RowGroup & row_group, const RowSubgroup & row_subgroup) const; + void fillConstantPagesAndDecodeRest( + ColumnChunk & column, const PrimitiveColumnInfo & column_info, + ColumnSubchunk & subchunk, const RowGroup & row_group, RowSubgroup & row_subgroup); + /// Returns mutable column because some of the recursive calls require it, /// e.g. ColumnArray::create does assumeMutable() on the nested columns. /// Moves the column out of ColumnSubchunk-s, leaving nullptrs in ColumnSubchunk::column. diff --git a/tests/queries/0_stateless/05815_parquet_constant_column_optimization.reference b/tests/queries/0_stateless/05815_parquet_constant_column_optimization.reference new file mode 100644 index 0000000000000..3328031ec73e1 --- /dev/null +++ b/tests/queries/0_stateless/05815_parquet_constant_column_optimization.reference @@ -0,0 +1,12 @@ +-- values, optimization on +42 hello 2020-01-02 03:04:05 7 1000 +-- values, optimization off (must be identical) +42 hello 2020-01-02 03:04:05 7 1000 +-- the varying column is read correctly (not treated as constant) +499500 0 999 1000 +-- filters on a constant column still work +1000 +0 +-- optimization fired only when enabled +1 +1 diff --git a/tests/queries/0_stateless/05815_parquet_constant_column_optimization.sh b/tests/queries/0_stateless/05815_parquet_constant_column_optimization.sh new file mode 100755 index 0000000000000..dc8820a69fbdf --- /dev/null +++ b/tests/queries/0_stateless/05815_parquet_constant_column_optimization.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +USER_FILES_PATH=$($CLICKHOUSE_CLIENT_BINARY --query "select _path,_file from file('nonexist.txt', 'CSV', 'val1 char')" 2>&1 | grep Exception | awk '{gsub("/nonexist.txt","",$9); print $9}') +WORKING_DIR="${USER_FILES_PATH}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +mkdir -p "${WORKING_DIR}" +DATA_FILE="${WORKING_DIR}/const.parquet" + +# 1000 rows, 100 rows per row group => 10 row groups. `k` varies; the other four columns each hold a +# single value in every row, so their per-chunk min/max statistics have min == max and no nulls. +# `c_dt` is written as TIMESTAMP_MILLIS and read back as DateTime, which needs a cast, so it is decoded +# normally (the optimization does not apply to it) and must read the same with the optimization on and off. +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) + SELECT + number AS k, + 42::Int64 AS c_int, + 'hello' AS c_str, + toDateTime('2020-01-02 03:04:05') AS c_dt, + 7::Nullable(Int64) AS c_nullable + FROM numbers(1000) + SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 100 +" + +STRUCTURE="k UInt64, c_int Int64, c_str String, c_dt DateTime, c_nullable Nullable(Int64)" + +qid_on="${CLICKHOUSE_TEST_UNIQUE_NAME}_on" +qid_off="${CLICKHOUSE_TEST_UNIQUE_NAME}_off" + +echo "-- values, optimization on" +${CLICKHOUSE_CLIENT} --query_id="${qid_on}" -q " + SELECT c_int, c_str, c_dt, c_nullable, count() + FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') + GROUP BY 1, 2, 3, 4 + SETTINGS input_format_parquet_verify_checksums = 0 +" + +echo "-- values, optimization off (must be identical)" +${CLICKHOUSE_CLIENT} --query_id="${qid_off}" -q " + SELECT c_int, c_str, c_dt, c_nullable, count() + FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') + GROUP BY 1, 2, 3, 4 + SETTINGS input_format_parquet_use_constant_column_optimization = 0, input_format_parquet_verify_checksums = 0 +" + +echo "-- the varying column is read correctly (not treated as constant)" +${CLICKHOUSE_CLIENT} -q "SELECT sum(k), min(k), max(k), count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') SETTINGS input_format_parquet_verify_checksums = 0" + +echo "-- filters on a constant column still work" +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_int = 42 SETTINGS input_format_parquet_verify_checksums = 0" +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_int = 43 SETTINGS input_format_parquet_verify_checksums = 0" + +echo "-- optimization fired only when enabled" +${CLICKHOUSE_CLIENT} -q " + SYSTEM FLUSH LOGS query_log; + SELECT ProfileEvents['ParquetConstantColumnChunks'] > 0 + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND query_id = '${qid_on}' AND type = 'QueryFinish' AND current_database = currentDatabase(); + SELECT ProfileEvents['ParquetConstantColumnChunks'] = 0 + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND query_id = '${qid_off}' AND type = 'QueryFinish' AND current_database = currentDatabase(); +" + +rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/05816_parquet_all_null_column_optimization.reference b/tests/queries/0_stateless/05816_parquet_all_null_column_optimization.reference new file mode 100644 index 0000000000000..dfda8ff8759cc --- /dev/null +++ b/tests/queries/0_stateless/05816_parquet_all_null_column_optimization.reference @@ -0,0 +1,14 @@ +-- all-null column, optimization on +1 1000 +-- all-null column, optimization off (must be identical) +1 1000 +-- the varying column is read correctly (not treated as constant) +499500 0 999 1000 +-- IS NULL / IS NOT NULL filters on an all-null column +1000 +0 +-- null_as_default: a non-nullable hint substitutes the default (0) for every row +0 1000 +-- optimization fired only when enabled +1 +1 diff --git a/tests/queries/0_stateless/05816_parquet_all_null_column_optimization.sh b/tests/queries/0_stateless/05816_parquet_all_null_column_optimization.sh new file mode 100755 index 0000000000000..1e29416cde529 --- /dev/null +++ b/tests/queries/0_stateless/05816_parquet_all_null_column_optimization.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +USER_FILES_PATH=$($CLICKHOUSE_CLIENT_BINARY --query "select _path,_file from file('nonexist.txt', 'CSV', 'val1 char')" 2>&1 | grep Exception | awk '{gsub("/nonexist.txt","",$9); print $9}') +WORKING_DIR="${USER_FILES_PATH}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +mkdir -p "${WORKING_DIR}" +DATA_FILE="${WORKING_DIR}/all_null.parquet" + +# 1000 rows, 100 rows per row group => 10 row groups. `k` varies; `c_null` is NULL in every row, so +# each of its column chunks has null_count == num_values and no min/max value. The reader +# materializes such chunks directly from statistics without fetching any data pages. +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) + SELECT + number AS k, + NULL::Nullable(Int64) AS c_null + FROM numbers(1000) + SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 100 +" + +STRUCTURE="k UInt64, c_null Nullable(Int64)" + +qid_on="${CLICKHOUSE_TEST_UNIQUE_NAME}_on" +qid_off="${CLICKHOUSE_TEST_UNIQUE_NAME}_off" + +echo "-- all-null column, optimization on" +${CLICKHOUSE_CLIENT} --query_id="${qid_on}" -q " + SELECT c_null IS NULL AS is_null, count() + FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') + GROUP BY 1 + SETTINGS input_format_parquet_verify_checksums = 0 +" + +echo "-- all-null column, optimization off (must be identical)" +${CLICKHOUSE_CLIENT} --query_id="${qid_off}" -q " + SELECT c_null IS NULL AS is_null, count() + FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') + GROUP BY 1 + SETTINGS input_format_parquet_use_constant_column_optimization = 0, input_format_parquet_verify_checksums = 0 +" + +echo "-- the varying column is read correctly (not treated as constant)" +${CLICKHOUSE_CLIENT} -q "SELECT sum(k), min(k), max(k), count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') SETTINGS input_format_parquet_verify_checksums = 0" + +echo "-- IS NULL / IS NOT NULL filters on an all-null column" +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_null IS NULL SETTINGS input_format_parquet_verify_checksums = 0" +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_null IS NOT NULL SETTINGS input_format_parquet_verify_checksums = 0" + +echo "-- null_as_default: a non-nullable hint substitutes the default (0) for every row" +${CLICKHOUSE_CLIENT} -q " + SELECT c_null, count() + FROM file('${DATA_FILE}', Parquet, 'k UInt64, c_null Int64') + GROUP BY 1 + SETTINGS input_format_null_as_default = 1, input_format_parquet_verify_checksums = 0 +" + +echo "-- optimization fired only when enabled" +${CLICKHOUSE_CLIENT} -q " + SYSTEM FLUSH LOGS query_log; + SELECT ProfileEvents['ParquetConstantColumnChunks'] > 0 + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND query_id = '${qid_on}' AND type = 'QueryFinish' AND current_database = currentDatabase(); + SELECT ProfileEvents['ParquetConstantColumnChunks'] = 0 + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND query_id = '${qid_off}' AND type = 'QueryFinish' AND current_database = currentDatabase(); +" + +rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/05817_parquet_constant_column_checksums.reference b/tests/queries/0_stateless/05817_parquet_constant_column_checksums.reference new file mode 100644 index 0000000000000..c39510a1fd971 --- /dev/null +++ b/tests/queries/0_stateless/05817_parquet_constant_column_checksums.reference @@ -0,0 +1,7 @@ +-- default settings: checksums are verified, so the optimization does not apply +42000 1000 +-- verification disabled: the optimization applies +42000 1000 +-- profile events +1 +1 diff --git a/tests/queries/0_stateless/05817_parquet_constant_column_checksums.sh b/tests/queries/0_stateless/05817_parquet_constant_column_checksums.sh new file mode 100755 index 0000000000000..40b103fad7643 --- /dev/null +++ b/tests/queries/0_stateless/05817_parquet_constant_column_checksums.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +USER_FILES_PATH=$($CLICKHOUSE_CLIENT_BINARY --query "select _path,_file from file('nonexist.txt', 'CSV', 'val1 char')" 2>&1 | grep Exception | awk '{gsub("/nonexist.txt","",$9); print $9}') +WORKING_DIR="${USER_FILES_PATH}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +mkdir -p "${WORKING_DIR}" +DATA_FILE="${WORKING_DIR}/checksums.parquet" + +# `c_int` holds 42 in every row, so its column chunks are constant according to their statistics. +# Constant chunks are materialized without reading their data pages, which would skip page checksum +# verification, so the optimization must not apply while input_format_parquet_verify_checksums is on. +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) + SELECT number AS k, 42::Int64 AS c_int + FROM numbers(1000) + SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 100 +" + +STRUCTURE="k UInt64, c_int Int64" + +qid_default="${CLICKHOUSE_TEST_UNIQUE_NAME}_default" +qid_no_verify="${CLICKHOUSE_TEST_UNIQUE_NAME}_no_verify" + +echo "-- default settings: checksums are verified, so the optimization does not apply" +${CLICKHOUSE_CLIENT} --query_id="${qid_default}" -q " + SELECT sum(c_int), count() + FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') + SETTINGS input_format_parquet_use_constant_column_optimization = 1 +" + +echo "-- verification disabled: the optimization applies" +${CLICKHOUSE_CLIENT} --query_id="${qid_no_verify}" -q " + SELECT sum(c_int), count() + FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') + SETTINGS input_format_parquet_use_constant_column_optimization = 1, input_format_parquet_verify_checksums = 0 +" + +echo "-- profile events" +${CLICKHOUSE_CLIENT} -q " + SYSTEM FLUSH LOGS query_log; + SELECT ProfileEvents['ParquetConstantColumnChunks'] = 0 + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND query_id = '${qid_default}' AND type = 'QueryFinish' AND current_database = currentDatabase(); + SELECT ProfileEvents['ParquetConstantColumnChunks'] > 0 + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND query_id = '${qid_no_verify}' AND type = 'QueryFinish' AND current_database = currentDatabase(); +" + +rm -rf "${WORKING_DIR}"