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..4b28a5e04dccf --- /dev/null +++ b/docs/design/parquet-v3-page-level-constant-column.md @@ -0,0 +1,134 @@ +--- +description: 'Design of the per-subgroup (page-level) constant-column optimization in the Parquet v3 reader.' +sidebarTitle: 'Parquet v3 page-level constants' +slug: /design/parquet-v3-page-level-constant-column +title: 'Parquet v3: page-level constant-column detection' +doc_type: 'reference' +--- + +# Parquet v3: per-subgroup (page-level) constant-column detection {#parquet-v3-per-subgroup-page-level-constant-column-detection} + +## Motivation {#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) {#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 (not needed, see Guardrails) | per subgroup | + +Tier 1 stays the always-on baseline. Tier 2 is opportunistic: only when the Column Index is already +loaded (or force-loaded, see below), only for chunks tier 1 did not already mark constant. Both tiers +cover `BYTE_ARRAY` / `FIXED_LEN_BYTE_ARRAY` strings, but neither applies `min == max` to floating-point +types (see Guardrails). + +## Key decision: do NOT change subgroup sizing {#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 {#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, string 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 {#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. + +The force-load is an explicit opt-in, so it does not honor `input_format_parquet_use_offset_index` or +`input_format_parquet_page_filter_push_down`: the Offset Index and Column Index are read for eligible +columns even when those are disabled. A malformed Column Index then fails the query even for a column +with no predicate; the error message names both `input_format_parquet_page_filter_push_down` and +`input_format_parquet_use_column_index_for_constant_columns` as the settings to turn off. + +## Cast safety (future-proofing) {#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 {#guardrails} + +- All types with a total order, 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. +- Not applied to `Float32` / `Float64` by `min == max`: floating-point has no total order. NaN is + excluded from the statistics (a chunk of `[1.0, NaN]` has `min == max == 1.0`), and `+0.0` and + `-0.0` compare equal (a page of `+0.0` values has `min = -0.0`, `max = +0.0` per the Parquet + spec, but would materialize as `-0.0`). Float columns are decoded normally unless the chunk or + page is all-null, which does not depend on `min` / `max`. +- 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 {#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. An all-null page is +filled only when the footer statistics allow nulls (a null map exists); a Column Index that contradicts +the footer (`null_count = 0` but an all-null page) is not trusted, and the page goes through the normal +decode path, which reports the inconsistency. Experimental, off by default. 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..788f890e23805 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. The Column Index and the Offset Index are read for these columns even if `input_format_parquet_use_offset_index` or `input_format_parquet_page_filter_push_down` is disabled, and a malformed Column Index then fails the query; disable this setting to ignore it. Applies only when `input_format_parquet_use_constant_column_optimization` is enabled and `input_format_parquet_verify_checksums` is disabled. +)", 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..ceb7b6e914f70 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, @@ -798,7 +798,12 @@ void ReadManager::scheduleTask(Task task, bool is_first_in_group, MemoryUsageDif break; /// Reads already issued in ColumnDataPrefetch; here just reserve estimated decoded-output /// memory against the ColumnData budget (runTask decodes from those buffers). - double bytes_per_row = reader.estimateColumnMemoryBytesPerRow(column, row_group, reader.primitive_columns.at(task.column_idx)); + /// A constant subchunk (tier 2; tier 1 is accounted for by the estimate itself) is a single + /// value and allocates nothing per row. + const auto & column_info = reader.primitive_columns.at(task.column_idx); + const bool single_value_subchunk = subchunk.is_constant + && Reader::constantIsSingleValueColumn(subchunk.is_all_null, column_info); + double bytes_per_row = single_value_subchunk ? 0. : reader.estimateColumnMemoryBytesPerRow(column, row_group, column_info); size_t column_memory = static_cast(bytes_per_row * static_cast(row_subgroup.filter.rows_pass)); subchunk.column_and_offsets_memory = MemoryUsageToken(column_memory, &diff); break; diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 4fe93f9570533..5e0d239826fbf 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); } } @@ -2009,12 +2033,25 @@ bool Reader::applyBloomAndDictionaryFilters(RowGroup & row_group, PruningMemoryR row_group.hyperrectangle, extended_sample_block_data_types, filter_map).can_be_true; } +/// Whether `min_value == max_value` in the statistics (chunk footer or per-page Column Index) +/// proves that every non-null value is that single value. That holds only for types with a total +/// order. It does not hold for Float32/Float64: NaN is excluded from the statistics, so a chunk of +/// [1.0, NaN] has min == max == 1.0, and +0.0 / -0.0 compare equal, so the bounds of a page of +0.0 +/// values (min = -0.0, max = +0.0 per the Parquet spec) look single-valued but would materialize as +/// -0.0. Such columns can still use the all-null shortcut, which does not rely on min/max. +static bool minMaxEqualityProvesSingleValue(const Reader::PrimitiveColumnInfo & column_info) +{ + return !WhichDataType(*column_info.decoded_type).isFloat(); +} + void Reader::applyColumnIndex(ColumnChunk & column, const PrimitiveColumnInfo & column_info, const RowGroup & row_group) { 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 +2069,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 +2089,18 @@ 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); + + /// Trust an all-null page only if a null map exists (`need_null_map` is false when the footer says + /// null_count == 0). A Column Index that contradicts the footer is left to the normal decode path, + /// which reports the inconsistency. + if (record_page_const) + column.page_const_info[page_idx].all_null = nullable && column.need_null_map && always_null; if (nullable && always_null) { @@ -2056,6 +2115,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 && minMaxEqualityProvesSingleValue(column_info) + && !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); @@ -2122,7 +2191,11 @@ void Reader::applyColumnIndex(ColumnChunk & column, const PrimitiveColumnInfo & column.row_ranges_after_column_index.emplace_back(0, size_t(row_group.meta->num_rows)); return; } - e.addMessage("in column index; use input_format_parquet_page_filter_push_down=0 to ignore"); + /// The Column Index is read for page-level predicate pruning (input_format_parquet_page_filter_push_down) + /// and/or for the constant-column optimization of every eligible column + /// (input_format_parquet_use_column_index_for_constant_columns); either setting can be the reason. + e.addMessage("in column index; use input_format_parquet_page_filter_push_down=0 and " + "input_format_parquet_use_column_index_for_constant_columns=0 to ignore"); throw; } } @@ -2307,6 +2380,33 @@ 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. + /// determinePagesToPrefetch then does not claim this subgroup's pages for the column + /// (a page shared with a non-constant neighbour is still fetched by that neighbour). + 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); + } + } + } } } row_group.intersected_row_ranges_after_column_index = std::move(row_ranges); @@ -2345,12 +2445,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 +2520,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) @@ -2463,8 +2590,19 @@ double Reader::estimateAverageStringLengthPerRow(const ColumnChunk & column, con return column_chunk_bytes / static_cast(row_group.meta->num_rows); } +bool Reader::constantIsSingleValueColumn(bool is_all_null, const PrimitiveColumnInfo & column_info) +{ + /// An all-null constant read into a non-nullable column is expanded by formOutputColumn to a full + /// column of defaults, because AddingDefaultsTransform replaces its rows with the column DEFAULT. + return !is_all_null || column_info.output_nullable; +} + double Reader::estimateColumnMemoryBytesPerRow(const ColumnChunk & column, const RowGroup & row_group, const PrimitiveColumnInfo & column_info) const { + /// A constant column chunk is never decoded: it is a single value, so it takes no memory per row. + if (column.is_constant && constantIsSingleValueColumn(column.is_all_null, column_info)) + return 0; + double res = 0; if (column_info.output_type->haveMaximumSizeOfValue()) /// Fixed-size values, e.g. numbers or FixedString. @@ -2485,8 +2623,373 @@ 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; + 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; + + /// min == max does not prove a single value for floating-point types (NaN is not reflected in + /// the statistics, +0.0 == -0.0), see minMaxEqualityProvesSingleValue. + if (!minMaxEqualityProvesSingleValue(column_info)) + 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); +} + +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_start >= end_row) + break; // this and all later pages are past the subgroup's row range + if (p_end <= start_row) + continue; + + 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_start >= end) + break; + if (p_end <= start) + 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). applyColumnIndex only records an all-null page when need_null_map is set, + /// so the null map exists here. + if (!null_map_data) + throw Exception(ErrorCodes::LOGICAL_ERROR, "All-null page in column {} has no null map to fill", column_info.name); + 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; its pages are not claimed for prefetch by + /// determinePagesToPrefetch). Skip decoding and hand the value to formOutputColumn, which + /// materializes it directly in the final output type. The value is in the output domain (no + /// cast is needed, see constColumnMaterializationEligible), 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.) + /// Count the optimization only where it takes effect: a row group that is pruned later or + /// read by another reader, and a subgroup with no rows left after the filters, never get here. + /// A whole-chunk constant is counted once, by the first subgroup served from it (the subgroups + /// of a column chunk are decoded one at a time). + if (!column.is_constant) + ProfileEvents::increment(ProfileEvents::ParquetConstantColumnSubchunks); + else if (!column.constant_event_reported) + { + column.constant_event_reported = true; + ProfileEvents::increment(ProfileEvents::ParquetConstantColumnChunks); + } + + 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 +3024,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 +3057,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 +3880,59 @@ 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); + + /// Only a non-nullable output substitutes the NULLs with the default (input_format_null_as_default), + /// so only then the rows are recorded in block_missing_values for AddingDefaultsTransform. A + /// Nullable output keeps its NULLs: the normal decode path drops the null map in + /// decodePrimitiveColumn (it is consumed by the ColumnNullable wrap) and never records them, so + /// AddingDefaultsTransform must not replace them with the DEFAULT either (for example with + /// input_format_defaults_for_omitted_fields). + const bool nulls_substituted_by_default = !primitive_columns.at(primitive_idx).output_nullable; + if (nulls_substituted_by_default + && 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); + /// AddingDefaultsTransform replaces the marked rows with the column's DEFAULT, and it + /// only handles full columns: on a ColumnConst, mixNumberColumns throws and mixColumns + /// leaves the value unchanged. So expand the constant here, as the normal path does. + result = result->convertToFullColumnIfConst(); + } + } + 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..1c08c4304bf9d 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.h +++ b/src/Processors/Formats/Impl/Parquet/Reader.h @@ -338,6 +338,37 @@ 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; + /// Whether ParquetConstantColumnChunks was already incremented for this chunk, which happens + /// when decodePrimitiveColumn first serves a subgroup from it. + bool constant_event_reported = 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 domain (columns that need a cast are not eligible, see + /// constColumnMaterializationEligible, so it is also the decoded domain). Empty when + /// unavailable. `is_const` is also set for truncatable physical types (BYTE_ARRAY / + /// FIXED_LEN_BYTE_ARRAY): bounds are always valid and truncation only widens them, so a + /// page with min_value == max_value holds one exact value even without a per-page + /// exactness flag. It is never set for floating-point types (see applyColumnIndex). + 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 +431,16 @@ 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 + /// domain; that is also the decoded domain, because constant columns never need a cast (see + /// constColumnMaterializationEligible). + 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 +651,51 @@ 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); + + /// Whether a constant chunk or subchunk (ColumnChunk::is_constant, ColumnSubchunk::is_constant) + /// is delivered as a single-value ColumnConst, which needs no memory per row. False for an + /// all-null one read into a non-nullable column, which formOutputColumn expands to a full column. + static bool constantIsSingleValueColumn(bool is_all_null, const PrimitiveColumnInfo & column_info); /// Guess how much memory ColumnSubchunk::{column, arrays_offsets} will use, per row. + /// Zero for a constant column chunk that is delivered as a single value. 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/00900_long_parquet_load_2.sh b/tests/queries/0_stateless/00900_long_parquet_load_2.sh index 60c89db7f961d..b9524bb24007f 100755 --- a/tests/queries/0_stateless/00900_long_parquet_load_2.sh +++ b/tests/queries/0_stateless/00900_long_parquet_load_2.sh @@ -81,6 +81,11 @@ EXCLUDE=( 05299_variant_read_as_json.parquet # Intentionally truncated variant blobs for the 05228 malformed-input test. 05228_variant_malformed.parquet + # The footer says there are no NULLs but the Column Index has an all-null page, on purpose, so + # loading it here would print an exception (05819). + 05819_parquet_fill_constant_pages_inconsistent_null_count.parquet + # The Column Index has min_value > max_value on purpose, so loading it here would print an exception (05820). + 05820_parquet_column_index_hint.parquet # Unsupported `VARIANT` specification version and one-sided null leaves, on purpose. 05306_variant_unsupported_version.parquet 05307_variant_one_sided_null.parquet 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}" diff --git a/tests/queries/0_stateless/05818_parquet_constant_column_float_stats.reference b/tests/queries/0_stateless/05818_parquet_constant_column_float_stats.reference new file mode 100644 index 0000000000000..2c362a069a9e2 --- /dev/null +++ b/tests/queries/0_stateless/05818_parquet_constant_column_float_stats.reference @@ -0,0 +1,9 @@ +-- floats with NaN and signed zeros, optimization on +500 500 500 500 500 1000 +-- optimization off (must be identical) +500 500 500 500 500 1000 +-- control: the integer column is materialized from its statistics +42000 1000 +-- float columns are not materialized as constants +1 +1 diff --git a/tests/queries/0_stateless/05818_parquet_constant_column_float_stats.sh b/tests/queries/0_stateless/05818_parquet_constant_column_float_stats.sh new file mode 100755 index 0000000000000..fcdb08dda918f --- /dev/null +++ b/tests/queries/0_stateless/05818_parquet_constant_column_float_stats.sh @@ -0,0 +1,68 @@ +#!/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}/float_stats.parquet" + +# Floating-point min/max statistics do not prove that a column chunk is single-valued: +# - NaN is not reflected in the statistics, so a chunk that alternates between 1.0 and NaN has +# min == max == 1.0; +# - +0.0 and -0.0 compare equal, so a chunk that alternates between them has min == max. +# The constant-column optimization must not materialize such columns as a single value. +# `c_int` holds 42 in every row and is the control: it is still materialized from its statistics. +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) + SELECT + number AS k, + if(number % 2 = 0, 1.0, nan)::Float64 AS f_nan, + if(number % 2 = 0, 1.0, nan)::Float32 AS f32_nan, + if(number % 2 = 0, 0.0, -0.0)::Float64 AS f_zero, + 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, f_nan Float64, f32_nan Float32, f_zero Float64, c_int Int64" + +qid_on="${CLICKHOUSE_TEST_UNIQUE_NAME}_on" +qid_off="${CLICKHOUSE_TEST_UNIQUE_NAME}_off" +qid_int="${CLICKHOUSE_TEST_UNIQUE_NAME}_int" + +QUERY=" + SELECT countIf(isNaN(f_nan)), countIf(f_nan = 1), countIf(isNaN(f32_nan)), countIf(1 / f_zero < 0), countIf(1 / f_zero > 0), count() + FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') +" + +echo "-- floats with NaN and signed zeros, optimization on" +${CLICKHOUSE_CLIENT} --query_id="${qid_on}" -q "${QUERY} SETTINGS input_format_parquet_verify_checksums = 0" + +echo "-- optimization off (must be identical)" +${CLICKHOUSE_CLIENT} --query_id="${qid_off}" -q "${QUERY} SETTINGS input_format_parquet_use_constant_column_optimization = 0, input_format_parquet_verify_checksums = 0" + +echo "-- control: the integer column is materialized from its statistics" +${CLICKHOUSE_CLIENT} --query_id="${qid_int}" -q " + SELECT sum(c_int), count() + FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') + SETTINGS input_format_parquet_verify_checksums = 0 +" + +echo "-- float columns are not materialized as constants" +${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_int}' AND type = 'QueryFinish' AND current_database = currentDatabase(); +" + +rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/05819_parquet_fill_constant_pages_inconsistent_null_count.reference b/tests/queries/0_stateless/05819_parquet_fill_constant_pages_inconsistent_null_count.reference new file mode 100644 index 0000000000000..be44aa979f669 --- /dev/null +++ b/tests/queries/0_stateless/05819_parquet_fill_constant_pages_inconsistent_null_count.reference @@ -0,0 +1,6 @@ +-- valid file: filling constant and all-null pages gives the same result as decoding them +385 10 40 +385 10 40 +-- inconsistent file: an error, with and without filling +ATTEMPT_TO_READ_AFTER_EOF +ATTEMPT_TO_READ_AFTER_EOF diff --git a/tests/queries/0_stateless/05819_parquet_fill_constant_pages_inconsistent_null_count.sh b/tests/queries/0_stateless/05819_parquet_fill_constant_pages_inconsistent_null_count.sh new file mode 100755 index 0000000000000..7dcf6373cab93 --- /dev/null +++ b/tests/queries/0_stateless/05819_parquet_fill_constant_pages_inconsistent_null_count.sh @@ -0,0 +1,56 @@ +#!/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}" + +VALID_FILE="${WORKING_DIR}/valid.parquet" +INCONSISTENT_FILE="${WORKING_DIR}/inconsistent.parquet" + +# A valid file with four data pages of 10 rows in the `v` column chunk: a page that only holds 7, +# a page that is entirely NULL, a page of distinct values, and another page that only holds 7. +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${VALID_FILE}', Parquet) + SELECT number AS k, multiIf(number < 10, 7, number < 20, NULL, number < 30, number, 7)::Nullable(Int64) AS v + FROM numbers(40) + SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 40, + output_format_parquet_data_page_size = 1, output_format_parquet_batch_size = 10, + output_format_parquet_compression_method = 'none', output_format_parquet_write_bloom_filter = 0 +" + +# The same file with the footer statistics patched to say that `v` has no NULLs (`null_count = 0`), +# while the Column Index of `v` still marks the second page as entirely NULL. The footer and the +# Column Index disagree. The data pages are untouched, so the NULL page really has no values. +cp "${CUR_DIR}/data_parquet/05819_parquet_fill_constant_pages_inconsistent_null_count.parquet" "${INCONSISTENT_FILE}" + +STRUCTURE="k UInt64, v Nullable(Int64)" +SETTINGS="input_format_parquet_verify_checksums = 0, input_format_parquet_use_column_index_for_constant_columns = 1, input_format_parquet_fill_constant_pages" + +echo "-- valid file: filling constant and all-null pages gives the same result as decoding them" +for fill in 0 1 +do + ${CLICKHOUSE_CLIENT} -q " + SELECT sum(v), countIf(v IS NULL), count() + FROM file('${VALID_FILE}', Parquet, '${STRUCTURE}') + SETTINGS ${SETTINGS} = ${fill} + " +done + +# The footer says there are no NULLs, so there is no null map for the all-null page. The reader must +# not fill that page from the Column Index; it reads it normally and reports the bad data. +echo "-- inconsistent file: an error, with and without filling" +for fill in 0 1 +do + ${CLICKHOUSE_CLIENT} -q " + SELECT sum(v), countIf(v IS NULL), count() + FROM file('${INCONSISTENT_FILE}', Parquet, '${STRUCTURE}') + SETTINGS ${SETTINGS} = ${fill} + " 2>&1 | grep -o -m1 'ATTEMPT_TO_READ_AFTER_EOF' +done + +rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/05820_parquet_column_index_hint.reference b/tests/queries/0_stateless/05820_parquet_column_index_hint.reference new file mode 100644 index 0000000000000..d507fd01a8592 --- /dev/null +++ b/tests/queries/0_stateless/05820_parquet_column_index_hint.reference @@ -0,0 +1,8 @@ +-- no predicate, constant columns do not use the Column Index: not read, not an error +385 40 +-- no predicate, the Column Index is read for the constant-column optimization +in column index; use input_format_parquet_page_filter_push_down=0 and input_format_parquet_use_column_index_for_constant_columns=0 to ignore +-- the same even if the offset index and page filtering are disabled +in column index; use input_format_parquet_page_filter_push_down=0 and input_format_parquet_use_column_index_for_constant_columns=0 to ignore +-- predicate on the column, page filtering only +in column index; use input_format_parquet_page_filter_push_down=0 and input_format_parquet_use_column_index_for_constant_columns=0 to ignore diff --git a/tests/queries/0_stateless/05820_parquet_column_index_hint.sh b/tests/queries/0_stateless/05820_parquet_column_index_hint.sh new file mode 100755 index 0000000000000..d25d83b002f86 --- /dev/null +++ b/tests/queries/0_stateless/05820_parquet_column_index_hint.sh @@ -0,0 +1,39 @@ +#!/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}" + +# A file whose Column Index of `v` is malformed: the third page has min_value = 29 > max_value = 20. +# The data pages and the footer are fine. +FILE="${WORKING_DIR}/bad_column_index.parquet" +cp "${CUR_DIR}/data_parquet/05820_parquet_column_index_hint.parquet" "${FILE}" + +STRUCTURE="k UInt64, v Nullable(Int64)" +COMMON="input_format_parquet_verify_checksums = 0" + +# Prints the hint from the error message, or `ok` if the query succeeded. +run() +{ + ${CLICKHOUSE_CLIENT} -q "SELECT sum(v), count() FROM file('${FILE}', Parquet, '${STRUCTURE}') $1 SETTINGS ${COMMON}, $2" 2>&1 \ + | grep -o -m1 'in column index; use .* to ignore' || true +} + +echo "-- no predicate, constant columns do not use the Column Index: not read, not an error" +${CLICKHOUSE_CLIENT} -q "SELECT sum(v), count() FROM file('${FILE}', Parquet, '${STRUCTURE}') SETTINGS ${COMMON}, input_format_parquet_use_column_index_for_constant_columns = 0" + +echo "-- no predicate, the Column Index is read for the constant-column optimization" +run "" "input_format_parquet_use_column_index_for_constant_columns = 1" + +echo "-- the same even if the offset index and page filtering are disabled" +run "" "input_format_parquet_use_column_index_for_constant_columns = 1, input_format_parquet_use_offset_index = 0, input_format_parquet_page_filter_push_down = 0" + +echo "-- predicate on the column, page filtering only" +run "WHERE v > 5" "input_format_parquet_use_column_index_for_constant_columns = 0" + +rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/05821_parquet_constant_subchunks.reference b/tests/queries/0_stateless/05821_parquet_constant_subchunks.reference new file mode 100644 index 0000000000000..95a4737d94518 --- /dev/null +++ b/tests/queries/0_stateless/05821_parquet_constant_subchunks.reference @@ -0,0 +1,24 @@ +-- reference result, the optimization is off +499500 4500 10 500 2500 4500 279250 +-- subgroups that are constant over their pages: the same result +499500 4500 10 500 2500 4500 279250 +-- GROUP BY on the constant columns: the same result with and without the optimization +same +0 v0 0 100 +1 v1 1 100 +2 v2 2 100 +-- filters on a column with the Column Index loaded for the predicate +300 110800 3 +300 110800 3 +-- the Column Index is loaded and constant subchunks are materialized +1 +-- no Column Index is loaded without the setting or a predicate: no constant subchunks +0 +-- the optimization is off: no constant subchunks +0 +-- a Float64 column is never materialized from the Column Index +0 +-- the mixed fill: the same result, and fewer data pages are read +279250 500 +279250 500 +1 diff --git a/tests/queries/0_stateless/05821_parquet_constant_subchunks.sh b/tests/queries/0_stateless/05821_parquet_constant_subchunks.sh new file mode 100755 index 0000000000000..626c209cd5e4d --- /dev/null +++ b/tests/queries/0_stateless/05821_parquet_constant_subchunks.sh @@ -0,0 +1,115 @@ +#!/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}/subchunks.parquet" + +# One row group of 1000 rows with data pages of 100 rows (the page ends after every batch because the +# page size limit is 1 byte). Page number p = number DIV 100. +# a: holds one value per page (clustered data). +# s: the same, as a string. +# n: Nullable; entirely NULL on even pages, and 5 on odd pages. +# f: the same as `a`, but Float64: `min == max` does not prove a single value for floating point. +# m: 9 on even pages, a varying value on odd pages (constant and varying pages are mixed). +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) + SELECT + number AS k, + intDiv(number, 100)::Int64 AS a, + concat('v', toString(intDiv(number, 100))) AS s, + if(intDiv(number, 100) % 2 = 0, NULL, 5)::Nullable(Int64) AS n, + intDiv(number, 100)::Float64 AS f, + if(intDiv(number, 100) % 2 = 0, 9, number)::Int64 AS m + FROM numbers(1000) + SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 1000, + output_format_parquet_data_page_size = 1, output_format_parquet_batch_size = 100, + output_format_parquet_compression_method = 'none', output_format_parquet_write_bloom_filter = 0 +" + +STRUCTURE="k UInt64, a Int64, s String, n Nullable(Int64), f Float64, m Int64" +# The constant-column optimization only applies when checksums are not verified. +BASE="input_format_parquet_verify_checksums = 0" +# Row subgroups of 100 rows are aligned with the pages. +TIER2="${BASE}, input_format_parquet_use_column_index_for_constant_columns = 1, input_format_parquet_max_block_size = 100" + +QUERY="SELECT sum(k), sum(a), uniqExact(s), countIf(n IS NULL), sum(n), sum(f), sum(m) FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}')" +GROUP_QUERY="SELECT a, s, f, count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') GROUP BY a, s, f ORDER BY a" + +echo "-- reference result, the optimization is off" +${CLICKHOUSE_CLIENT} -q "${QUERY} SETTINGS input_format_parquet_use_constant_column_optimization = 0, ${BASE}" + +echo "-- subgroups that are constant over their pages: the same result" +${CLICKHOUSE_CLIENT} -q "${QUERY} SETTINGS ${TIER2}" + +echo "-- GROUP BY on the constant columns: the same result with and without the optimization" +${CLICKHOUSE_CLIENT} -q "${GROUP_QUERY} SETTINGS input_format_parquet_use_constant_column_optimization = 0, ${BASE}" > "${WORKING_DIR}/group_off.tsv" +${CLICKHOUSE_CLIENT} -q "${GROUP_QUERY} SETTINGS ${TIER2}" > "${WORKING_DIR}/group_on.tsv" +cmp "${WORKING_DIR}/group_off.tsv" "${WORKING_DIR}/group_on.tsv" && echo "same" +head -n 3 "${WORKING_DIR}/group_on.tsv" + +echo "-- filters on a column with the Column Index loaded for the predicate" +${CLICKHOUSE_CLIENT} -q "SELECT count(), sum(m), uniqExact(s) FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE a IN (2, 3, 7) SETTINGS ${TIER2}" +${CLICKHOUSE_CLIENT} -q "SELECT count(), sum(m), uniqExact(s) FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE a IN (2, 3, 7) SETTINGS input_format_parquet_use_constant_column_optimization = 0, ${BASE}" + +# Run a query with the given settings and print how many subchunks were materialized as constants +# (`> 0` or `= 0`) and how many data pages were read. +run_with_events() +{ + local name="$1" + local query="$2" + local settings="$3" + ${CLICKHOUSE_CLIENT} --query_id="${CLICKHOUSE_TEST_UNIQUE_NAME}_${name}" -q "${query} SETTINGS ${settings}" > /dev/null +} + +event() +{ + ${CLICKHOUSE_CLIENT} -q " + SELECT ProfileEvents['$2'] + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND query_id = '${CLICKHOUSE_TEST_UNIQUE_NAME}_$1' AND type = 'QueryFinish' AND current_database = currentDatabase() + " +} + +run_with_events tier2 "${QUERY}" "${TIER2}" +run_with_events no_force "${QUERY}" "${BASE}, input_format_parquet_max_block_size = 100" +run_with_events off "${QUERY}" "input_format_parquet_use_constant_column_optimization = 0, ${TIER2}" +run_with_events float "SELECT sum(f), count() FROM file('${DATA_FILE}', Parquet, 'f Float64')" "${TIER2}" +run_with_events fill_on "SELECT sum(m), countIf(n IS NULL) FROM file('${DATA_FILE}', Parquet, 'm Int64, n Nullable(Int64)')" \ + "${BASE}, input_format_parquet_use_column_index_for_constant_columns = 1, input_format_parquet_max_block_size = 150, input_format_parquet_fill_constant_pages = 1" +run_with_events fill_off "SELECT sum(m), countIf(n IS NULL) FROM file('${DATA_FILE}', Parquet, 'm Int64, n Nullable(Int64)')" \ + "${BASE}, input_format_parquet_use_column_index_for_constant_columns = 1, input_format_parquet_max_block_size = 150, input_format_parquet_fill_constant_pages = 0" + +${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH LOGS query_log" + +echo "-- the Column Index is loaded and constant subchunks are materialized" +event tier2 ParquetConstantColumnSubchunks | awk '{print ($1 > 0)}' +echo "-- no Column Index is loaded without the setting or a predicate: no constant subchunks" +event no_force ParquetConstantColumnSubchunks +echo "-- the optimization is off: no constant subchunks" +event off ParquetConstantColumnSubchunks +echo "-- a Float64 column is never materialized from the Column Index" +event float ParquetConstantColumnSubchunks + +echo "-- the mixed fill: the same result, and fewer data pages are read" +${CLICKHOUSE_CLIENT} -q " + SELECT sum(m), countIf(n IS NULL) + FROM file('${DATA_FILE}', Parquet, 'm Int64, n Nullable(Int64)') + SETTINGS ${BASE}, input_format_parquet_use_column_index_for_constant_columns = 1, input_format_parquet_max_block_size = 150, input_format_parquet_fill_constant_pages = 1 +" +${CLICKHOUSE_CLIENT} -q " + SELECT sum(m), countIf(n IS NULL) + FROM file('${DATA_FILE}', Parquet, 'm Int64, n Nullable(Int64)') + SETTINGS input_format_parquet_use_constant_column_optimization = 0, ${BASE} +" +fill_on_pages=$(event fill_on ParquetReadPages) +fill_off_pages=$(event fill_off ParquetReadPages) +echo "$((fill_on_pages < fill_off_pages))" + +rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/05822_parquet_constant_null_as_default.reference b/tests/queries/0_stateless/05822_parquet_constant_null_as_default.reference new file mode 100644 index 0000000000000..96b6e02ec9fe0 --- /dev/null +++ b/tests/queries/0_stateless/05822_parquet_constant_null_as_default.reference @@ -0,0 +1,24 @@ +-- constant-column optimization 0 +0 42 42 x +1 42 1 x +2 42 42 x +3 42 3 x +4 42 42 x +5 42 5 x +-- constant-column optimization 1 +0 42 42 x +1 42 1 x +2 42 42 x +3 42 3 x +4 42 42 x +5 42 5 x +-- checksums are verified (normal decode), for comparison +0 42 42 x +1 42 1 x +2 42 42 x +3 42 3 x +4 42 42 x +5 42 5 x +-- the constant path is used only with the optimization +0 +1 diff --git a/tests/queries/0_stateless/05822_parquet_constant_null_as_default.sh b/tests/queries/0_stateless/05822_parquet_constant_null_as_default.sh new file mode 100755 index 0000000000000..95c78c02ffb39 --- /dev/null +++ b/tests/queries/0_stateless/05822_parquet_constant_null_as_default.sh @@ -0,0 +1,78 @@ +#!/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}/nulls.parquet" + +# One row group with a single data page per column. `allnull` is entirely NULL, so its chunk is +# materialized as a constant (no data pages are read). `mixed` has NULLs and values. +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) + SELECT + number AS k, + CAST(NULL AS Nullable(Int64)) AS allnull, + if(number % 2 = 0, NULL, number)::Nullable(Int64) AS mixed, + CAST(NULL AS Nullable(String)) AS allnull_s + FROM numbers(6) + SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 100, + output_format_parquet_compression_method = 'none' +" + +# The target columns are not Nullable and have a DEFAULT. With input_format_null_as_default, the +# NULLs of the file are read as the column DEFAULT, and with input_format_defaults_for_omitted_fields +# the rows marked as defaulted get the DEFAULT expression. +SETTINGS="--input_format_defaults_for_omitted_fields=1 --input_format_null_as_default=1" + +for optimization in 0 1 +do + echo "-- constant-column optimization ${optimization}" + ${CLICKHOUSE_CLIENT} -q "DROP TABLE IF EXISTS t_${optimization}" + ${CLICKHOUSE_CLIENT} -q " + CREATE TABLE t_${optimization} (k UInt64, allnull Int64 DEFAULT 42, mixed Int64 DEFAULT 42, allnull_s String DEFAULT 'x') + ENGINE = MergeTree ORDER BY k + " + ${CLICKHOUSE_CLIENT} ${SETTINGS} --input_format_parquet_verify_checksums=0 \ + --input_format_parquet_use_constant_column_optimization=${optimization} \ + --query_id="${CLICKHOUSE_TEST_UNIQUE_NAME}_${optimization}" --query "INSERT INTO t_${optimization} FORMAT Parquet" < "${DATA_FILE}" + ${CLICKHOUSE_CLIENT} -q "SELECT k, allnull, mixed, allnull_s FROM t_${optimization} ORDER BY k" + ${CLICKHOUSE_CLIENT} -q "DROP TABLE t_${optimization}" +done + +echo "-- checksums are verified (normal decode), for comparison" +${CLICKHOUSE_CLIENT} -q "DROP TABLE IF EXISTS t_checksums" +${CLICKHOUSE_CLIENT} -q " + CREATE TABLE t_checksums (k UInt64, allnull Int64 DEFAULT 42, mixed Int64 DEFAULT 42, allnull_s String DEFAULT 'x') + ENGINE = MergeTree ORDER BY k +" +${CLICKHOUSE_CLIENT} ${SETTINGS} --input_format_parquet_verify_checksums=1 \ + --query "INSERT INTO t_checksums FORMAT Parquet" < "${DATA_FILE}" +${CLICKHOUSE_CLIENT} -q "SELECT k, allnull, mixed, allnull_s FROM t_checksums ORDER BY k" +${CLICKHOUSE_CLIENT} -q "DROP TABLE t_checksums" + +# Check the constant path with a SELECT that reads the all-null column (count() alone reads no columns). +echo "-- the constant path is used only with the optimization" +for optimization in 0 1 +do + ${CLICKHOUSE_CLIENT} --query_id="${CLICKHOUSE_TEST_UNIQUE_NAME}_select_${optimization}" -q " + SELECT countIf(allnull IS NULL) FROM file('${DATA_FILE}', Parquet, 'k UInt64, allnull Nullable(Int64), mixed Nullable(Int64), allnull_s Nullable(String)') + SETTINGS input_format_parquet_verify_checksums = 0, input_format_parquet_use_constant_column_optimization = ${optimization} + " > /dev/null +done +${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH LOGS query_log" +for optimization in 0 1 +do + ${CLICKHOUSE_CLIENT} -q " + SELECT ProfileEvents['ParquetConstantColumnChunks'] > 0 + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND query_id = '${CLICKHOUSE_TEST_UNIQUE_NAME}_select_${optimization}' AND type = 'QueryFinish' AND current_database = currentDatabase() + " +done + +rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/05823_parquet_constant_nullable_target_defaults.reference b/tests/queries/0_stateless/05823_parquet_constant_nullable_target_defaults.reference new file mode 100644 index 0000000000000..66c865cc11eb3 --- /dev/null +++ b/tests/queries/0_stateless/05823_parquet_constant_nullable_target_defaults.reference @@ -0,0 +1,8 @@ +-- constant-column optimization 0 +300 150 0 32300 300 0 12600 +-- constant-column optimization 1 +300 150 0 32300 300 0 12600 +-- checksums are verified (normal decode), for comparison +300 150 0 32300 300 0 12600 +-- the constant path is used +1 1 diff --git a/tests/queries/0_stateless/05823_parquet_constant_nullable_target_defaults.sh b/tests/queries/0_stateless/05823_parquet_constant_nullable_target_defaults.sh new file mode 100755 index 0000000000000..2b9037512d105 --- /dev/null +++ b/tests/queries/0_stateless/05823_parquet_constant_nullable_target_defaults.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash + +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}/nulls.parquet" + +# One row group of 300 rows, with small data pages so that every subgroup of 100 rows is a whole run of pages. +# `a` is NULL in rows 0..99 (an all-null run of pages inside a row group that is not all-null: materialized per +# subgroup), mixed in rows 100..199, and non-null in rows 200..299. `b` and `c` are entirely NULL (materialized per +# column chunk). +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) + SELECT + number AS k, + if(number < 100, NULL, if(number < 200, if(number % 2 = 0, NULL, number), number))::Nullable(Int64) AS a, + CAST(NULL AS Nullable(String)) AS b, + CAST(NULL AS Nullable(Int64)) AS c + FROM numbers(300) + SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 300, + output_format_parquet_data_page_size = 1, output_format_parquet_batch_size = 10, + output_format_parquet_compression_method = 'none', output_format_parquet_write_bloom_filter = 0 +" + +# `a` and `b` are Nullable and have a DEFAULT: their NULLs must be kept, not replaced by the DEFAULT. `c` is not +# Nullable: its NULLs are substituted by the DEFAULT (input_format_null_as_default). +for optimization in 0 1 +do + echo "-- constant-column optimization ${optimization}" + ${CLICKHOUSE_CLIENT} -q "DROP TABLE IF EXISTS t_${optimization}" + ${CLICKHOUSE_CLIENT} -q " + CREATE TABLE t_${optimization} (k UInt64, a Nullable(Int64) DEFAULT 42, b Nullable(String) DEFAULT 'x', c Int64 DEFAULT 42) + ENGINE = MergeTree ORDER BY k + " + ${CLICKHOUSE_CLIENT} --input_format_defaults_for_omitted_fields=1 --input_format_null_as_default=1 \ + --input_format_parquet_verify_checksums=0 --input_format_parquet_use_constant_column_optimization=${optimization} \ + --input_format_parquet_use_column_index_for_constant_columns=1 --input_format_parquet_max_block_size=100 \ + --query_id="${CLICKHOUSE_TEST_UNIQUE_NAME}_${optimization}" --query "INSERT INTO t_${optimization} FORMAT Parquet" < "${DATA_FILE}" + ${CLICKHOUSE_CLIENT} -q "SELECT count(), countIf(a IS NULL), countIf(a = 42), sum(ifNull(a, -1)), countIf(b IS NULL), countIf(b = 'x'), sum(c) FROM t_${optimization}" + ${CLICKHOUSE_CLIENT} -q "DROP TABLE t_${optimization}" +done + +echo "-- checksums are verified (normal decode), for comparison" +${CLICKHOUSE_CLIENT} -q "DROP TABLE IF EXISTS t_checksums" +${CLICKHOUSE_CLIENT} -q " + CREATE TABLE t_checksums (k UInt64, a Nullable(Int64) DEFAULT 42, b Nullable(String) DEFAULT 'x', c Int64 DEFAULT 42) + ENGINE = MergeTree ORDER BY k +" +${CLICKHOUSE_CLIENT} --input_format_defaults_for_omitted_fields=1 --input_format_null_as_default=1 \ + --input_format_parquet_verify_checksums=1 \ + --query "INSERT INTO t_checksums FORMAT Parquet" < "${DATA_FILE}" +${CLICKHOUSE_CLIENT} -q "SELECT count(), countIf(a IS NULL), countIf(a = 42), sum(ifNull(a, -1)), countIf(b IS NULL), countIf(b = 'x'), sum(c) FROM t_checksums" +${CLICKHOUSE_CLIENT} -q "DROP TABLE t_checksums" + +# Check that the constant path is used (per-subgroup for `a`, per-chunk for `b` and `c`), by reading the same file +# with the optimization on. +echo "-- the constant path is used" +${CLICKHOUSE_CLIENT} --query_id="${CLICKHOUSE_TEST_UNIQUE_NAME}_select" -q " + SELECT countIf(a IS NULL), countIf(b IS NULL), countIf(c IS NULL) + FROM file('${DATA_FILE}', Parquet, 'k UInt64, a Nullable(Int64), b Nullable(String), c Nullable(Int64)') + SETTINGS input_format_parquet_verify_checksums = 0, input_format_parquet_use_constant_column_optimization = 1, + input_format_parquet_use_column_index_for_constant_columns = 1, input_format_parquet_max_block_size = 100 +" > /dev/null +${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH LOGS query_log" +${CLICKHOUSE_CLIENT} -q " + SELECT ProfileEvents['ParquetConstantColumnSubchunks'] > 0, ProfileEvents['ParquetConstantColumnChunks'] > 0 + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND query_id = '${CLICKHOUSE_TEST_UNIQUE_NAME}_select' AND type = 'QueryFinish' AND current_database = currentDatabase() +" + +rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/05824_parquet_constant_column_block_size.reference b/tests/queries/0_stateless/05824_parquet_constant_column_block_size.reference new file mode 100644 index 0000000000000..558bd66fae2f0 --- /dev/null +++ b/tests/queries/0_stateless/05824_parquet_constant_column_block_size.reference @@ -0,0 +1,6 @@ +-- the constant column is read in as many blocks as when it is not read at all +1 +-- the same column decoded needs more, smaller blocks +1 +-- the values are correct +100000 4999950000 1 100 diff --git a/tests/queries/0_stateless/05824_parquet_constant_column_block_size.sh b/tests/queries/0_stateless/05824_parquet_constant_column_block_size.sh new file mode 100755 index 0000000000000..4476ac9f0d86e --- /dev/null +++ b/tests/queries/0_stateless/05824_parquet_constant_column_block_size.sh @@ -0,0 +1,49 @@ +#!/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}/block_size.parquet" + +# One row group. `n` varies; `s` is a long constant string, which the reader estimates as a large column +# when sizing the blocks (`input_format_parquet_prefer_block_bytes`) although a constant column is +# never decoded. The block size must therefore be the same as if `s` was not read at all. +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) + SELECT number AS n, repeat('x', 100) AS s + FROM numbers(100000) + SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 100000 +" + +SETTINGS="max_threads = 1, input_format_parquet_verify_checksums = 0, input_format_parquet_prefer_block_bytes = 200000" + +blocks_n_only=$(${CLICKHOUSE_CLIENT} -q " + SELECT uniqExact(blockNumber()), sum(n) > 0 FROM file('${DATA_FILE}', Parquet, 'n UInt64') + SETTINGS ${SETTINGS} +" | cut -f1) +blocks_constant=$(${CLICKHOUSE_CLIENT} -q " + SELECT uniqExact(blockNumber()), sum(n) > 0, sum(length(s)) > 0 FROM file('${DATA_FILE}', Parquet, 'n UInt64, s String') + SETTINGS ${SETTINGS} +" | cut -f1) +blocks_decoded=$(${CLICKHOUSE_CLIENT} -q " + SELECT uniqExact(blockNumber()), sum(n) > 0, sum(length(s)) > 0 FROM file('${DATA_FILE}', Parquet, 'n UInt64, s String') + SETTINGS ${SETTINGS}, input_format_parquet_use_constant_column_optimization = 0 +" | cut -f1) + +echo "-- the constant column is read in as many blocks as when it is not read at all" +echo "$((blocks_constant == blocks_n_only))" +echo "-- the same column decoded needs more, smaller blocks" +echo "$((blocks_decoded > blocks_n_only))" + +echo "-- the values are correct" +${CLICKHOUSE_CLIENT} -q " + SELECT count(), sum(n), uniqExact(s), min(length(s)) FROM file('${DATA_FILE}', Parquet, 'n UInt64, s String') + SETTINGS ${SETTINGS} +" + +rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/05825_parquet_constant_column_events.reference b/tests/queries/0_stateless/05825_parquet_constant_column_events.reference new file mode 100644 index 0000000000000..cef5cd6e9d970 --- /dev/null +++ b/tests/queries/0_stateless/05825_parquet_constant_column_events.reference @@ -0,0 +1,9 @@ +-- rows pass the PREWHERE: the chunk constant and the page constants are used +1 +1 +-- no row passes the PREWHERE: nothing is served from the constants +0 +0 +-- the results +500 21000 2250 +0 0 0 diff --git a/tests/queries/0_stateless/05825_parquet_constant_column_events.sh b/tests/queries/0_stateless/05825_parquet_constant_column_events.sh new file mode 100755 index 0000000000000..4ea4a5202e8f9 --- /dev/null +++ b/tests/queries/0_stateless/05825_parquet_constant_column_events.sh @@ -0,0 +1,63 @@ +#!/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}/events.parquet" + +# One row group of 1000 rows with data pages of 100 rows. +# n: varies. +# c: the same value in the whole column chunk (constant according to the column chunk statistics). +# a: one value per page (constant per page, according to the Column Index). +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) + SELECT number AS n, 42::Int64 AS c, intDiv(number, 100)::Int64 AS a + FROM numbers(1000) + SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 1000, + output_format_parquet_data_page_size = 1, output_format_parquet_batch_size = 100, + output_format_parquet_compression_method = 'none', output_format_parquet_write_bloom_filter = 0 +" + +SETTINGS="input_format_parquet_verify_checksums = 0, input_format_parquet_use_column_index_for_constant_columns = 1, input_format_parquet_max_block_size = 100" +STRUCTURE="n UInt64, c Int64, a Int64" + +# The constant columns are only counted when a block is actually served from them, not when the optimization is +# detected: a PREWHERE that removes every row never decodes them. +${CLICKHOUSE_CLIENT} --query_id="${CLICKHOUSE_TEST_UNIQUE_NAME}_served" -q " + SELECT count(), sum(c), sum(a) FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') PREWHERE n % 2 = 0 + SETTINGS ${SETTINGS} +" > /dev/null +${CLICKHOUSE_CLIENT} --query_id="${CLICKHOUSE_TEST_UNIQUE_NAME}_filtered" -q " + SELECT count(), sum(c), sum(a) FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') PREWHERE n % 2 = 5 + SETTINGS ${SETTINGS} +" > /dev/null + +${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH LOGS query_log" + +event() +{ + ${CLICKHOUSE_CLIENT} -q " + SELECT ProfileEvents['$2'] > 0 + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND query_id = '${CLICKHOUSE_TEST_UNIQUE_NAME}_$1' AND type = 'QueryFinish' AND current_database = currentDatabase() + " +} + +echo "-- rows pass the PREWHERE: the chunk constant and the page constants are used" +event served ParquetConstantColumnChunks +event served ParquetConstantColumnSubchunks +echo "-- no row passes the PREWHERE: nothing is served from the constants" +event filtered ParquetConstantColumnChunks +event filtered ParquetConstantColumnSubchunks + +echo "-- the results" +${CLICKHOUSE_CLIENT} -q "SELECT count(), sum(c), sum(a) FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') PREWHERE n % 2 = 0 SETTINGS ${SETTINGS}" +${CLICKHOUSE_CLIENT} -q "SELECT count(), sum(c), sum(a) FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') PREWHERE n % 2 = 5 SETTINGS ${SETTINGS}" + +rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/data_parquet/05819_parquet_fill_constant_pages_inconsistent_null_count.parquet b/tests/queries/0_stateless/data_parquet/05819_parquet_fill_constant_pages_inconsistent_null_count.parquet new file mode 100644 index 0000000000000..eca6437bd2db3 Binary files /dev/null and b/tests/queries/0_stateless/data_parquet/05819_parquet_fill_constant_pages_inconsistent_null_count.parquet differ diff --git a/tests/queries/0_stateless/data_parquet/05820_parquet_column_index_hint.parquet b/tests/queries/0_stateless/data_parquet/05820_parquet_column_index_hint.parquet new file mode 100644 index 0000000000000..4e75d41ef6442 Binary files /dev/null and b/tests/queries/0_stateless/data_parquet/05820_parquet_column_index_hint.parquet differ