From 65385ee5b2d1fe36377259265f9660b5c69e67d8 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Wed, 5 Aug 2026 18:12:07 +0300 Subject: [PATCH 01/20] Parquet v3: materialize constant column chunks from statistics When a Parquet column chunk provably holds a single value in every row - its min/max statistics have `min_value == max_value`, no nulls, and the value is exact - the reader no longer fetches or decodes that chunk's data pages. Instead `detectConstantColumn` records the value and `decodePrimitiveColumn`/`formOutputColumn` materialize it directly. This skips the offset index, column index, dictionary page and data page reads for such chunks (the row group already passed the key condition via its `min == max` hyperrectangle), which is a byte-level I/O win for wide constant columns, plus the decode/decompression CPU. Restricted to flat, top-level primitive columns with no element nulls. For `BYTE_ARRAY`/`FIXED_LEN_BYTE_ARRAY` the writer may truncate min/max, so `min == max` is trusted only when `is_min_value_exact` and `is_max_value_exact` are both set; fixed-width numeric types are never truncated. The value is taken from `PageDecoderInfo::decodeField`, which yields it in the final output (post-cast) domain - e.g. `DateTime` written as `TIMESTAMP_MILLIS` decodes to seconds, not the raw millisecond `decoded_type`. So the constant is materialized directly in the output type, bypassing the `decoded_type` column and `castColumn`. Gated by the new setting `input_format_parquet_use_constant_column_optimization` (default on). A new `ParquetConstantColumnChunks` ProfileEvent counts materialized chunks. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/Common/ProfileEvents.cpp | 1 + src/Core/FormatFactorySettings.h | 3 + src/Core/SettingsChangesHistory.cpp | 28 +++++ src/Formats/FormatFactory.cpp | 1 + src/Formats/FormatSettings.h | 1 + .../Formats/Impl/Parquet/Reader.cpp | 115 ++++++++++++++++-- src/Processors/Formats/Impl/Parquet/Reader.h | 20 +++ ...uet_constant_column_optimization.reference | 12 ++ ...11_parquet_constant_column_optimization.sh | 69 +++++++++++ 9 files changed, 243 insertions(+), 7 deletions(-) create mode 100644 tests/queries/0_stateless/04811_parquet_constant_column_optimization.reference create mode 100755 tests/queries/0_stateless/04811_parquet_constant_column_optimization.sh diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index c9b79615610b7..eeaedf97978aa 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1847,6 +1847,7 @@ 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(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..62425263254c3 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -235,6 +235,9 @@ 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. )", 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..4830563f98c29 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -133,6 +133,19 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() {"throw_on_hive_partitioning_resolution_failure", false, true, "New setting to fail the query when Hive-style partitioning detection for an object storage table cannot list the storage, instead of running without the Hive partition columns."}, {"enable_json_ast_dialect", false, false, "New setting to enable the `clickhouse_json` value of the `dialect` setting, which interprets queries as JSON ASTs (the output of `parseQueryToJSON`) instead of SQL text."}, {"allow_metadata_only_named_tuple_alter", false, false, "New setting to control metadata-only ALTER for named Tuple subfield additions."}, + addSettingsChanges(settings_changes_history, "26.8", + { + {"max_insert_threads", 1, 0, "Changed the default from 1 (no parallel execution) to auto (0), which resolves to the number of CPU cores available to the server, reduced under memory pressure via `max_insert_threads_min_free_memory_per_thread`. This parallelizes `INSERT SELECT` by default. Set to 1 to restore the previous single-threaded behavior."}, + {"unique_key_probe_implementation", "auto", "auto", "New setting: selects the UNIQUE KEY probe implementation (currently only the simple baseline exists)"}, + {"s3_base", "", "", "New setting to specify the base URL for resolving relative URLs in the s3 table function and the S3 table engine."}, + {"use_query_condition_cache_for_top_k", false, false, "New setting to gate the query condition cache for `ORDER BY ... LIMIT n` (TopK) reads; disabled by default."}, + {"use_projection_index_in_read_pools", false, false, "New setting to drop mark ranges fully filtered out by a projection index before read tasks are created in MergeTree read pools."}, + {"allow_distinct_partitions_independently", false, true, "New setting to enable independent per-partition evaluation of `DISTINCT` when the partition expression is a deterministic function of the `DISTINCT` columns."}, + {"force_distinct_partitions_independently", false, false, "New setting to force independent per-partition evaluation of `DISTINCT` even when the cost heuristic would skip it."}, + {"max_number_of_partitions_for_independent_distinct", 128, 128, "New setting: maximal number of partitions to apply independent per-partition `DISTINCT`."}, + {"allow_lossy_numeric_supertype", false, false, "New setting that lets if/multiIf/coalesce/ifNull/array/map resolve all-numeric branches with no lossless common type (e.g. Decimal + Float64) to a numeric supertype (Float64, with possible precision loss), so the result can be aggregated. Independent of use_variant_as_common_type: with it off such branches previously raised NO_COMMON_TYPE, with it on they became a Variant; either way they now resolve to Float64."}, + {"throw_on_hive_partitioning_resolution_failure", false, true, "New setting to fail the query when Hive-style partitioning detection for an object storage table cannot list the storage, instead of running without the Hive partition columns."}, + {"allow_experimental_json_ast_dialect", false, false, "New setting to enable the `clickhouse_json` value of the `dialect` setting, which interprets queries as JSON ASTs (the output of `parseQueryToJSON`) instead of SQL text."}, {"analyzer_compatibility_apply_final_to_all_joined_tables", false, false, "New setting on master (default false = the fixed behavior). The behavior flip itself is recorded under 26.6, and the introduction for backports to older release branches (with default true) under 26.4."}, {"enable_parallel_single_level_merge", false, true, "New setting to parallelize the final merge of the single-level aggregation hash tables by splitting the key space into disjoint hash partitions that the threads merge independently."}, {"ai_function_text_default_credentials", "", "", "New setting"}, @@ -167,6 +180,9 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() {"input_format_json_max_object_size", 512 * 1024 * 1024, 512 * 1024 * 1024, "New setting to limit the maximum size of a single JSON object in bytes"}, {"format_hive_text_rows_delimiter", "\n", "\n", "New setting for the delimiter at the end of each row in the HiveText output format."}, {"output_format_parquet_wide_integer_as_decimal", false, false, "New setting to write `Int128`, `UInt128`, `Int256`, and `UInt256` values as standard Parquet `DECIMAL` values. The previous value keeps the legacy little-endian `FIXED_LEN_BYTE_ARRAY` representation."}, + {"ai_function_allow_insecure_endpoint", true, false, "AI functions now reject insecure (http) endpoints to remote hosts by default."}, + {"ai_function_max_api_calls_per_query", 0, 1000, "Bound outbound AI function HTTP calls per query by default (previously 0 - unlimited)."}, + {"join_runtime_filter_min_probe_rows", 0, 1000, "New setting to control minimum probe side size for installing JOIN runtime filters. It wasn't limited before, so previous value is 0 meaning always install."}, {"optimize_trivial_count_with_sparsity_filter", false, true, "Promote to BETA and enable by default: serve `SELECT count() FROM t WHERE ` from the persisted per-column `num_defaults` / `num_rows` counters when `` partitions rows into defaults vs non-defaults. Requires the MergeTree setting `compute_exact_num_defaults_for_sparse_columns` (also enabled by default now)."}, {"input_format_parquet_dictionary_filter_push_down", 0, 1024 * 1024, "New setting enabling Parquet row-group pruning based on dictionary page contents (reader v3). The value is the maximum dictionary page size in bytes for which the optimization applies; 0 (the previous behavior) disables it."}, {"input_format_read_datetime_number_as_raw_value", true, false, "From 26.8, an unquoted number for a `DateTime`/`DateTime64` column in the `JSON` and `Values`/`Quoted` paths (and in `JSONExtract` and typed `JSON`) is a Unix timestamp in seconds, consistent with the `Values` format, `CAST` and `toDateTime64`. Set this to `true` (or `SET compatibility = '26.7'`) to restore the pre-26.8 behavior, where a bare unquoted integer fed to a `DateTime64` column was read as the raw scaled value (ticks). The tab-separated, CSV and other escaped/whole-text formats are not governed by this setting."}, @@ -208,6 +224,16 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() {"query_plan_optimize_lazy_materialization_for_object_storage", false, true, "New setting to use lazy materialization for `ORDER BY ... LIMIT n` queries reading Parquet files from object storage (including Iceberg tables)."}, {"iceberg_compaction_max_rows_in_data_file", std::numeric_limits::max(), std::numeric_limits::max(), "New setting for the max rows of an iceberg data file produced by compaction, separate from the insert-time limit."}, {"iceberg_compaction_max_bytes_in_data_file", std::numeric_limits::max(), std::numeric_limits::max(), "New setting for the max bytes of an iceberg data file produced by compaction, separate from the insert-time limit."}, + {"input_format_arrow_use_native_reader", true, true, "Obsolete setting, the native ClickHouse reader is now always used for the `Arrow` and `ArrowStream` formats (the Apache Arrow library-based reader has been removed)."}, + {"output_format_arrow_use_native_writer", true, true, "Obsolete setting, the native ClickHouse writer is now always used for the `Arrow` and `ArrowStream` formats (the Apache Arrow library-based writer has been removed)."}, + {"distributed_cache_min_inflight_bytes_to_discard_connection_on_seek", 0, 4 * 1024 * 1024, "New setting to drop and reopen a distributed cache connection on a seek when too many in-flight bytes would otherwise be discarded. Defaults to 4 MiB; 0 restores the previous behavior (always reuse the connection via the read range id)."}, + {"input_format_parquet_spatial_filter_push_down", false, true, "New setting: skip GeoParquet row groups and pages based on spatial predicates and bounding box statistics"}, + {"use_text_index_negative_tokens_cache", false, true, "New setting to cache absent text index tokens and avoid repeated dictionary lookups."}, + {"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 (reader v3)."}, + }); + addSettingsChanges(settings_changes_history, "26.7", + { + {"analyzer_compatibility_allow_non_aggregate_in_having", false, false, "New compatibility setting. When enabled, the analyzer mimics the legacy `HAVING`-to-`WHERE` rewrite for non-aggregate AND-conjuncts instead of raising `NOT_AN_AGGREGATE`."}, {"dictionary_lazy_load", "auto", "auto", "New setting overriding the server setting `dictionaries_lazy_load` for an individual dictionary."}, {"discard_query_data", false, false, "New setting to skip sending query result rows to the client over the native TCP protocol."}, {"optimize_trivial_count_with_sparsity_filter", false, false, "New (experimental) setting to serve `SELECT count() FROM t WHERE ` from per-column `num_defaults` / `num_rows` recorded in `serialization.json` when `` partitions rows into defaults vs non-defaults."}, @@ -273,6 +299,8 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() {"object_storage_cluster_fallback_to_local_if_empty", false, false, "New setting"}, {"use_puffin_files_cache", false, true, "Enables cache of parsed Puffin file content such as deletion vectors."}, }); + }); + addSettingsChanges(settings_changes_history, "26.6", { {"analyzer_compatibility_apply_final_to_all_joined_tables", true, false, "Fixed a bug in the analyzer where FINAL on the left-most table of a JOIN was incorrectly applied to the other joined tables as well. previous_value=true so `compatibility` with versions before 26.6 restores the old behavior."}, diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index c169db9af1df1..da10fef9b0bd9 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -231,6 +231,7 @@ 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.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..b8c7db0b5e166 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -386,6 +386,7 @@ 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 enable_json_parsing = true; bool preserve_order = false; diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 4fe93f9570533..84514cec21810 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -55,6 +55,7 @@ namespace ProfileEvents extern const Event ParquetColumnsFilterExpression; extern const Event ParquetReadPages; extern const Event ParquetPrunedPages; + extern const Event ParquetConstantColumnChunks; } namespace DB::Parquet @@ -862,6 +863,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 +1074,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 +1154,13 @@ 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. + /// Offset index. - if (use_offset_index && + if (use_offset_index && !column.is_constant && column.meta->__isset.offset_index_offset && column.meta->__isset.offset_index_length) { column.offset_index_prefetch = prefetcher.registerRange( @@ -1159,7 +1169,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() && column.offset_index_prefetch && column.meta->__isset.column_index_offset && column.meta->__isset.column_index_length; if (column.use_column_index) @@ -1179,10 +1190,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); } } @@ -2348,6 +2360,8 @@ 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) { 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 @@ -2485,8 +2499,83 @@ double Reader::estimateColumnMemoryBytesPerRow(const ColumnChunk & column, const return res; } +void Reader::detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInfo & column_info) const +{ + if (!options.format.parquet.use_constant_column_optimization) + return; + /// We rely on column chunk min/max statistics being both present and decodable. + if (!column_info.decoder.allow_stats) + return; + + /// Only flat, top-level primitive columns. Nested columns (arrays, tuples, maps) and + /// physically-nullable structs carry repetition/definition level information that we would skip + /// by not reading the pages, so restrict to the simple case where "value" == "row". + if (column_info.levels.size() != 1 || column_info.group_nullable) + return; + if (column_info.levels.back().is_array || column_info.levels.back().rep != 0) + return; + + const auto & meta_data = column.meta->meta_data; + if (!meta_data.__isset.statistics) + return; + const auto & stats = meta_data.statistics; + + /// All rows must be non-null. A chunk with both a value and some nulls has two distinct logical + /// values and still needs a null map. (An all-null chunk is a separate, not-yet-handled case.) + if (!stats.__isset.null_count || stats.null_count != 0) + return; + + if (!stats.__isset.min_value || !stats.__isset.max_value) + return; + if (stats.min_value != stats.max_value) + return; + + /// For BYTE_ARRAY / FIXED_LEN_BYTE_ARRAY the writer may store truncated min/max, which could make + /// two different values compare equal. Trust min == max only when the writer marked both exact. + /// Fixed-width numeric types are never truncated, so min == max is always exact for them. + const bool may_be_truncated = + meta_data.type == parq::Type::BYTE_ARRAY || meta_data.type == parq::Type::FIXED_LEN_BYTE_ARRAY; + if (may_be_truncated + && !(stats.__isset.is_min_value_exact && stats.is_min_value_exact + && stats.__isset.is_max_value_exact && stats.is_max_value_exact)) + return; + + Field value; + column_info.decoder.decodeField(stats.min_value, /*is_max=*/ false, value); + /// decodeField leaves `value` unchanged (Null) if the physical type is unsupported for stats. + if (value.isNull()) + return; + + column.is_constant = true; + column.constant_value = std::move(value); + ProfileEvents::increment(ProfileEvents::ParquetConstantColumnChunks); +} + void Reader::decodePrimitiveColumn(ColumnChunk & column, const PrimitiveColumnInfo & column_info, ColumnSubchunk & subchunk, const RowGroup & row_group, RowSubgroup & row_subgroup, MemoryUsageDiff & diff) { + if (column.is_constant) + { + /// This chunk provably holds a single value in every row (see detectConstantColumn), and its + /// data pages were never fetched. Skip all decoding and hand the already-decoded value to + /// formOutputColumn, which materializes it directly in the final output type. The value is + /// in the output (post-cast) domain, so it must not go through the decoded_type column and + /// castColumn path. We still run the per-output-column bookkeeping below so the output column + /// is formed once the last of its primitive columns is done. + subchunk.is_constant = true; + subchunk.constant_value = column.constant_value; + + 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; @@ -3363,6 +3452,18 @@ 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): materialize the single value + /// directly in the final output type. The value is already in the output (post-cast) + /// domain, so we skip the decoded_type column and the castColumn below. The chunk has no + /// nulls, so there is nothing to record in block_missing_values. + auto constant_column = output_info.output_type->createColumn(); + constant_column->insertMany(subchunk.constant_value, num_rows); + return constant_column; + } + 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..e0730314dba86 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.h +++ b/src/Processors/Formats/Impl/Parquet/Reader.h @@ -338,6 +338,13 @@ 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; + /// Prefetches. /// TODO [parquet]: Check that all handles and tokens are reset after correct stages. PrefetchHandle bloom_filter_header_prefetch; @@ -400,6 +407,13 @@ struct Reader /// Primitive column. MutableColumnPtr column; + /// Set by decodePrimitiveColumn when the source column chunk is constant (see + /// ColumnChunk::is_constant): `column` is then left empty and formOutputColumn materializes + /// `constant_value` directly in the final output type. `constant_value` is in the output + /// (post-cast) domain. + bool is_constant = false; + Field constant_value; + MutableColumnPtr null_map; /// For a leaf of a physically-nullable struct read as Nullable(Tuple(...)) (see @@ -617,6 +631,12 @@ struct Reader 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. Uses column chunk min/max statistics (Tier 1). Only applies to + /// flat, top-level primitive columns with no element nulls; see the implementation for the + /// exact conditions. + void detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInfo & column_info) const; + /// 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/04811_parquet_constant_column_optimization.reference b/tests/queries/0_stateless/04811_parquet_constant_column_optimization.reference new file mode 100644 index 0000000000000..3328031ec73e1 --- /dev/null +++ b/tests/queries/0_stateless/04811_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/04811_parquet_constant_column_optimization.sh b/tests/queries/0_stateless/04811_parquet_constant_column_optimization.sh new file mode 100755 index 0000000000000..2a059de021871 --- /dev/null +++ b/tests/queries/0_stateless/04811_parquet_constant_column_optimization.sh @@ -0,0 +1,69 @@ +#!/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 with a DateTime hint, exercising the +# milliseconds -> seconds stats conversion (the value is in the post-cast output domain). +${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 +" + +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 +" + +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}')" + +echo "-- filters on a constant column still work" +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_int = 42" +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_int = 43" + +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}" From 349e1ee1c1a4b2de5d8768dddf457da2ea8099d0 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Thu, 6 Aug 2026 05:00:34 +0300 Subject: [PATCH 02/20] Parquet v3: fix constant-column detection gates (never fired) Two gate bugs made detectConstantColumn reject every column, so the optimization never triggered on real files. Found by building and testing against CH-written Parquet. 1. Null gate. The CH writer omits `null_count` for physically non-nullable (`REQUIRED`) columns, but the gate required `null_count` to be present and zero, rejecting every non-nullable column. A `REQUIRED` column can have no nulls regardless of the statistic, so only require zero `null_count` when the column is physically nullable (max definition level > 0). 2. Structural gate. `levels[0]` is a synthetic root sentinel with `is_array = true`, so a flat `REQUIRED` column's `levels.back()` IS that root (`size() == 1`, `is_array == true`) and a `Nullable` column has `size() == 2`. The old `levels.size() == 1 && !levels.back().is_array` test therefore rejected exactly the flat columns it meant to accept. Replace with the correct flatness signals (`levels.back().rep == 0` and `max_array_def == 0`), keep the `group_nullable` exclusion, and require the output column to be primitive (top-level, not a Tuple/Map/Array leaf) via `output_columns`. Verified on a CH-written file (1M rows, constant Int64/String/DateTime/ Nullable columns): the optimization now fires (`ParquetConstantColumnChunks` = columns x row groups), results are correct (including the TIMESTAMP_MILLIS -> DateTime seconds path), reading the constant columns drops `ParquetPrefetcherReadRandomRead` 10 -> 1 and `ParquetDecodingTasks` 96 -> 64, and a varying column is correctly not treated as constant. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../Formats/Impl/Parquet/Reader.cpp | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 84514cec21810..26ada291f6913 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2507,12 +2507,19 @@ void Reader::detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInf if (!column_info.decoder.allow_stats) return; - /// Only flat, top-level primitive columns. Nested columns (arrays, tuples, maps) and - /// physically-nullable structs carry repetition/definition level information that we would skip - /// by not reading the pages, so restrict to the simple case where "value" == "row". - if (column_info.levels.size() != 1 || column_info.group_nullable) + /// 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; - if (column_info.levels.back().is_array || column_info.levels.back().rep != 0) + if (column_info.idx_in_output_block >= sample_block_to_output_columns_idx.size()) + return; + 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; const auto & meta_data = column.meta->meta_data; @@ -2520,9 +2527,13 @@ void Reader::detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInf return; const auto & stats = meta_data.statistics; - /// All rows must be non-null. A chunk with both a value and some nulls has two distinct logical + /// 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. (An all-null chunk is a separate, not-yet-handled case.) - if (!stats.__isset.null_count || stats.null_count != 0) + bool physically_nullable = column_info.levels.back().def > 0; + if (physically_nullable && (!stats.__isset.null_count || stats.null_count != 0)) return; if (!stats.__isset.min_value || !stats.__isset.max_value) From d0d384b20dd0a778db70935fd914feca2ad7b2a4 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Thu, 6 Aug 2026 17:16:35 +0300 Subject: [PATCH 03/20] Parquet v3: materialize all-null column chunks from statistics Extends the constant-column optimization to the all-null case. When a Parquet column chunk provably holds only nulls - its `null_count` statistic equals `num_values` on a physically nullable leaf - the reader no longer fetches or decodes that chunk's dictionary or data pages. `detectConstantColumn` marks the chunk constant (and `is_all_null`), and `formOutputColumn` materializes the result directly: `Null` for a Nullable output, or the output default when `input_format_null_as_default` substitutes nulls for a non-nullable output. A non-nullable output without null substitution cannot represent the result, so such a chunk is left to the normal decode path. Unlike the single-value case this needs no value decode, so it sidesteps the min/max exactness and `BYTE_ARRAY` truncation checks entirely; it only reads the `null_count` count. `formOutputColumn` records every row of an all-null chunk in `block_missing_values` (the single-value case has no nulls and records nothing), matching the normal decode path's null-map bookkeeping so `input_format_null_as_default` stays correct. All-null wide chunks are common in schema-evolved files (a column added later is all-null in older row groups), so this skips dictionary, data page, offset index and column index reads for a frequent real-world shape. Reuses the existing `input_format_parquet_use_constant_column_optimization` setting and the `ParquetConstantColumnChunks` ProfileEvent. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- .../Formats/Impl/Parquet/Reader.cpp | 43 ++++++++++- src/Processors/Formats/Impl/Parquet/Reader.h | 15 +++- ...uet_all_null_column_optimization.reference | 14 ++++ ...12_parquet_all_null_column_optimization.sh | 73 +++++++++++++++++++ 4 files changed, 138 insertions(+), 7 deletions(-) create mode 100644 tests/queries/0_stateless/04812_parquet_all_null_column_optimization.reference create mode 100755 tests/queries/0_stateless/04812_parquet_all_null_column_optimization.sh diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 26ada291f6913..8d332cb498be8 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2527,12 +2527,38 @@ void Reader::detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInf return; const auto & stats = meta_data.statistics; + bool physically_nullable = column_info.levels.back().def > 0; + + /// All-null chunk: every row is null (null_count == num_values). This is provable only for a + /// physically nullable leaf (a REQUIRED column can have no nulls), and only when the writer + /// emitted the null_count statistic. No value is decoded at all, so this skips the min/max + /// exactness and truncation concerns below. We materialize `Null` for a Nullable output, or the + /// output default when `null_as_default` substitutes nulls for a non-nullable output; a + /// non-nullable output without null substitution cannot represent the result, so we leave the + /// chunk to the normal decode path (which errors on the null). formOutputColumn records every + /// row in block_missing_values for this case. + if (physically_nullable && stats.__isset.null_count && stats.null_count == meta_data.num_values + && meta_data.num_values > 0) + { + const bool null_as_default = options.format.null_as_default && !column_info.output_nullable; + if (column_info.output_nullable) + column.constant_value = Null{}; + else if (null_as_default) + column.constant_value = column_info.output_type->getDefault(); + else + return; + + column.is_constant = true; + column.is_all_null = true; + ProfileEvents::increment(ProfileEvents::ParquetConstantColumnChunks); + return; + } + /// All rows must be non-null. If the parquet column is physically nullable (max definition level /// > 0), require the statistics to prove zero nulls. If it is REQUIRED (definition level 0) there /// can be no nulls, so the null_count statistic - which writers commonly omit for non-nullable /// columns - is unnecessary. A chunk that mixes the value with nulls has two distinct logical - /// values and still needs a null map. (An all-null chunk is a separate, not-yet-handled case.) - bool physically_nullable = column_info.levels.back().def > 0; + /// values and still needs a null map. if (physically_nullable && (!stats.__isset.null_count || stats.null_count != 0)) return; @@ -2574,6 +2600,7 @@ void Reader::decodePrimitiveColumn(ColumnChunk & column, const PrimitiveColumnIn /// is formed once the last of its primitive columns is done. subchunk.is_constant = true; subchunk.constant_value = column.constant_value; + subchunk.is_all_null = column.is_all_null; OutputColumnState & state = row_subgroup.output.at(column_info.idx_in_output_block); chassert(!state.column); @@ -3468,10 +3495,18 @@ MutableColumnPtr Reader::formOutputColumn(RowSubgroup & row_subgroup, size_t out { /// Constant column chunk (see detectConstantColumn): materialize the single value /// directly in the final output type. The value is already in the output (post-cast) - /// domain, so we skip the decoded_type column and the castColumn below. The chunk has no - /// nulls, so there is nothing to record in block_missing_values. + /// domain, so we skip the decoded_type column and the castColumn below. auto constant_column = output_info.output_type->createColumn(); constant_column->insertMany(subchunk.constant_value, num_rows); + + /// An all-null chunk must record every row in block_missing_values, matching the normal + /// decode path (which records nulls from the null map); needed for + /// input_format_null_as_default. The single-value case has no nulls, so records nothing. + if (subchunk.is_all_null + && 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); + return constant_column; } diff --git a/src/Processors/Formats/Impl/Parquet/Reader.h b/src/Processors/Formats/Impl/Parquet/Reader.h index e0730314dba86..4431c36cdfea3 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.h +++ b/src/Processors/Formats/Impl/Parquet/Reader.h @@ -344,6 +344,11 @@ struct Reader /// 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; /// Prefetches. /// TODO [parquet]: Check that all handles and tokens are reset after correct stages. @@ -413,6 +418,8 @@ struct Reader /// (post-cast) domain. bool is_constant = false; Field constant_value; + /// Mirror of ColumnChunk::is_all_null (see there). + bool is_all_null = false; MutableColumnPtr null_map; @@ -632,9 +639,11 @@ struct Reader 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. Uses column chunk min/max statistics (Tier 1). Only applies to - /// flat, top-level primitive columns with no element nulls; see the implementation for the - /// exact conditions. + /// 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; /// Returns mutable column because some of the recursive calls require it, diff --git a/tests/queries/0_stateless/04812_parquet_all_null_column_optimization.reference b/tests/queries/0_stateless/04812_parquet_all_null_column_optimization.reference new file mode 100644 index 0000000000000..dfda8ff8759cc --- /dev/null +++ b/tests/queries/0_stateless/04812_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/04812_parquet_all_null_column_optimization.sh b/tests/queries/0_stateless/04812_parquet_all_null_column_optimization.sh new file mode 100755 index 0000000000000..21522716651db --- /dev/null +++ b/tests/queries/0_stateless/04812_parquet_all_null_column_optimization.sh @@ -0,0 +1,73 @@ +#!/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 +" + +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 +" + +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}')" + +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" +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_null IS NOT NULL" + +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 +" + +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}" From 48cb87d3675efabf462f753e4429cfffda5a8d47 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 17:33:07 +0300 Subject: [PATCH 04/20] Parquet v3: materialize constant column chunks as ColumnConst formOutputColumn previously expanded a constant column chunk with insertMany(Field, num_rows) - an O(rows) per-row Field-dispatch fill that showed up as a consistent ~20% UserTime increase in profiling (the baseline decoded the same near-constant chunk cheaply via RLE/dictionary). Emit a ColumnConst instead: O(1) to build, and the const-ness propagates through the pipeline. A PREWHERE/WHERE predicate computes its result from the value without expanding the stored column, and GROUP BY / aggregation over the column get a const key. The value is already in the output (post-cast) domain. The all-null block_missing_values bookkeeping is unchanged. The reader path preserves the const: getOrFormOutputColumn returns it as-is, ColumnConst::size() == rows_pass satisfies the delivery checks, and ColumnConst::filter keeps it const through multistage PREWHERE. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- src/Processors/Formats/Impl/Parquet/Reader.cpp | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 8d332cb498be8..b25ba1c56d52f 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 @@ -3493,11 +3494,14 @@ MutableColumnPtr Reader::formOutputColumn(RowSubgroup & row_subgroup, size_t out if (subchunk.is_constant) { - /// Constant column chunk (see detectConstantColumn): materialize the single value - /// directly in the final output type. The value is already in the output (post-cast) - /// domain, so we skip the decoded_type column and the castColumn below. - auto constant_column = output_info.output_type->createColumn(); - constant_column->insertMany(subchunk.constant_value, num_rows); + /// 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. The value is already in the output + /// (post-cast) domain, so we skip the decoded_type column and the castColumn below. + MutableColumnPtr single_value = output_info.output_type->createColumn(); + single_value->insert(subchunk.constant_value); /// An all-null chunk must record every row in block_missing_values, matching the normal /// decode path (which records nulls from the null map); needed for @@ -3507,7 +3511,7 @@ MutableColumnPtr Reader::formOutputColumn(RowSubgroup & row_subgroup, size_t out && *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); - return constant_column; + return ColumnConst::create(std::move(single_value), num_rows); } res = std::move(subchunk.column); From 3c79bb32e69a1acbc5673e66b0546b5f845aefbc Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 19:04:05 +0300 Subject: [PATCH 05/20] Parquet v3: per-subgroup (page-level) constant-column detection [tier 2] Extends the constant-column optimization from whole-chunk (tier 1, footer statistics) to per-row-subgroup granularity using the Column Index per-page min/max/null_pages, which the reader already loads for predicate push-down. Catches columns constant over a run of pages without the whole row group being constant (common in sorted/clustered data), with no change to subgroup/chunk sizing. - constColumnMaterializationEligible: shared flat-top-level-primitive gate, factored out of detectConstantColumn. - applyColumnIndex: retain per-page constant info (value / is_const / all_null) in ColumnChunk::page_const_info. Fixed-width numeric/date/time only for value constants (the Column Index has no per-page exactness flag, so a truncated BYTE_ARRAY min==max is untrustworthy); all_null is a plain flag, always safe. - detectConstantSubchunk: a column is constant for a subgroup iff every page overlapping the subgroup row range is all-null, or all hold the same value. - Wired into intersectColumnIndexResultsAndInitSubgroups; sets the subchunk constant fields so decodePrimitiveColumn skips decode and formOutputColumn materializes a ColumnConst. New ParquetConstantColumnSubchunks ProfileEvent. Tier 1 stays the always-on baseline and the only detector for BYTE_ARRAY. Tier 2 is opportunistic: only where the Column Index is already loaded (predicate push-down columns), never force-fetched. Deferred (follow-up): skipping the prefetch of constant subgroups pages (the I/O win). Currently those pages are still fetched and skipped forward by the next subgroups skipToRowOrNextPage; correct but does not yet save the read. Design: docs/design/parquet-v3-page-level-constant-column.md Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- .../parquet-v3-page-level-constant-column.md | 70 ++++++++ src/Common/ProfileEvents.cpp | 1 + .../Formats/Impl/Parquet/Reader.cpp | 169 ++++++++++++++++-- src/Processors/Formats/Impl/Parquet/Reader.h | 27 +++ 4 files changed, 254 insertions(+), 13 deletions(-) create mode 100644 docs/design/parquet-v3-page-level-constant-column.md 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..218490336f93e --- /dev/null +++ b/docs/design/parquet-v3-page-level-constant-column.md @@ -0,0 +1,70 @@ +# Parquet v3: per-subgroup (page-level) constant-column detection + +## Motivation + +The current constant-column optimization (`detectConstantColumn`) fires only when a whole +Parquet **column chunk** is single-valued (footer `min == max`, no nulls). Data that is sorted or +clustered on a column is often constant over long **runs of pages** without the whole row group +being constant, so chunk-level detection misses it. + +Parquet's **Column Index** stores per-page `min_values` / `max_values` / `null_pages` / +`null_counts`. The v3 reader already loads and parses it (`applyColumnIndex`) for predicate +push-down, so per-page "is this page constant?" is available at zero extra I/O. This lets us mark a +column constant for the row range of an individual **row subgroup** (the unit that becomes one +output `Chunk`) and materialize it as a `ColumnConst`, skipping the covered pages' reads and decode. + +## Tiers (both kept) + +| Tier | Source | Always present? | Exact flag? | Granularity | +|------|--------|-----------------|-------------|-------------| +| 1 (existing) | footer `ColumnMetaData.statistics` | yes | yes (`is_min_value_exact`) | whole chunk | +| 2 (this doc) | Column Index (per page) | no (optional) | no | per subgroup | + +Tier 1 stays the always-on baseline and the **only** safe detector for `BYTE_ARRAY` / +`FIXED_LEN_BYTE_ARRAY` (Column Index has no per-page exactness flag; 16-byte truncation can make two +distinct strings compare equal). Tier 2 is opportunistic: only for fixed-width numeric/date/time, +only when the Column Index is already loaded, only for chunks tier 1 did not already mark constant. + +## Key decision: do NOT change subgroup sizing + +Aligning subgroups to page boundaries would fragment the block stream into many tiny chunks +(pages are far smaller than a row group), and a subgroup carries all columns so its size is bounded +by the non-constant columns anyway. Instead, keep subgroup boundaries exactly as today and do +**per-subgroup, per-column** detection: a column is constant for a subgroup iff every Column-Index +page overlapping the subgroup's row range is constant with the *same* value (or every such page is +`null_pages`). Chunk count is unchanged; we just catch subgroups that sit inside a constant run. + +## Phases + +- **Phase 0** — retain per-page constant info. `applyColumnIndex` currently discards the parsed + `parq::ColumnIndex`. Keep a compact per-page summary on `ColumnChunk` (value + `is_const` + + `all_null`), plus the page→`first_row_index` map already in the Offset Index. Populate only for + eligible types. +- **Phase 1** — `detectConstantSubchunk(column, column_info, [start_row, end_row))`: scan the pages + overlapping the range; return constant + value when all are `is_const` and share one value; + all-null when all are `null_pages`. +- **Phase 2** — call it in `intersectColumnIndexResultsAndInitSubgroups` for each subgroup / + primitive column that tier 1 didn't already mark constant; set `subchunk.is_constant` / + `is_all_null` / `constant_value` (the same fields `decodePrimitiveColumn` propagates). + `formOutputColumn` needs no change (already emits `ColumnConst`). +- **Phase 3** — skip work for constant subchunks: `decodePrimitiveColumn` skips decode on + `subchunk.is_constant`; `determinePagesToPrefetch` skips fetching a page only when it is constant + in **every** subgroup that overlaps it. +- **Phase 4** — stateless tests (page-run constant, all-null-per-page, byte-array negative/truncation + guard, `GROUP BY` correctness), with a new `ParquetConstantColumnSubchunks` ProfileEvent to prove + tier 2 fired. +- **Phase 5** — ProfileEvents comparison on clustered data: expect further `S3GetObject` / + `ParquetFetchWaitTimeMicroseconds` drops with chunk count unchanged. + +## Guardrails + +- Fixed-width numeric/date/time only (truncation). +- Reuse the Column Index only when already loaded; never force-fetch it just for this. +- Gate on the existing `input_format_parquet_use_constant_column_optimization` setting. +- 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. + +## Out of scope + +In-subgroup partial fill for constant runs *shorter* than a subgroup (skip only those pages' bytes, +yield a full column) — a later follow-up. diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index eeaedf97978aa..d4bd1e9e71482 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1848,6 +1848,7 @@ The server successfully detected this situation and will download merged part fr 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/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index b25ba1c56d52f..9a26a16944a93 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -57,6 +57,7 @@ namespace ProfileEvents extern const Event ParquetReadPages; extern const Event ParquetPrunedPages; extern const Event ParquetConstantColumnChunks; + extern const Event ParquetConstantColumnSubchunks; } namespace DB::Parquet @@ -2045,6 +2046,18 @@ 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). For truncatable physical types the Column Index has no per-page + /// exactness flag, so a per-page min == max is untrustworthy: record only `all_null` there. + const bool record_page_const = + constColumnMaterializationEligible(column_info) && !column.is_constant; + const bool may_be_truncated = + column.meta->meta_data.type == parq::Type::BYTE_ARRAY + || column.meta->meta_data.type == parq::Type::FIXED_LEN_BYTE_ARRAY; + 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; @@ -2056,6 +2069,9 @@ void Reader::applyColumnIndex(ColumnChunk & column, const PrimitiveColumnInfo & 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; + if (record_page_const) + column.page_const_info[page_idx].all_null = always_null; + if (nullable && always_null) { /// Single-point range containing either the default value or one of the infinities. @@ -2069,6 +2085,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 && !may_be_truncated && !can_be_null + && !range.left.isNull() && range.left == range.right) + { + column.page_const_info[page_idx].is_const = true; + column.page_const_info[page_idx].value = range.left; + } + /// Nullability is checked against each extracted condition below. A nullable /// ClickHouse output can therefore keep the finite range from the column index. adjustRangeFromIndexIfNeeded(range, column_info, can_be_null && !column_info.output_nullable); @@ -2320,6 +2346,34 @@ void Reader::intersectColumnIndexResultsAndInitSubgroups(RowGroup & row_group) } if (options.format.defaults_for_omitted_fields) row_subgroup.block_missing_values.init(sample_block->columns()); + + /// Tier 2 constant detection: for each primitive column not already whole-chunk-constant + /// (tier 1), check whether it is constant over this subgroup's row range using the + /// per-page Column Index info retained in applyColumnIndex. If so, mark the subchunk so + /// decodePrimitiveColumn skips decoding it and formOutputColumn materializes a ColumnConst. + /// The subgroup's pages are still skipped forward by the next subgroup's + /// skipToRowOrNextPage; skipping the prefetch itself is a separate follow-up. + if (row_group.need_to_process) + { + for (size_t i = 0; i < primitive_columns.size(); ++i) + { + ColumnChunk & column = row_group.columns[i]; + if (column.is_constant) + continue; // tier 1 already materializes the whole chunk + bool all_null = false; + Field value; + if (detectConstantSubchunk( + column, primitive_columns[i], substart, subend, + size_t(row_group.meta->num_rows), all_null, value)) + { + ColumnSubchunk & subchunk = row_subgroup.columns[i]; + subchunk.is_constant = true; + subchunk.is_all_null = all_null; + subchunk.constant_value = std::move(value); + ProfileEvents::increment(ProfileEvents::ParquetConstantColumnSubchunks); + } + } + } } } row_group.intersected_row_ranges_after_column_index = std::move(row_ranges); @@ -2500,13 +2554,13 @@ double Reader::estimateColumnMemoryBytesPerRow(const ColumnChunk & column, const return res; } -void Reader::detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInfo & column_info) const +bool Reader::constColumnMaterializationEligible(const PrimitiveColumnInfo & column_info) const { if (!options.format.parquet.use_constant_column_optimization) - return; - /// We rely on column chunk min/max statistics being both present and decodable. + return false; + /// We rely on min/max statistics being both present and decodable. if (!column_info.decoder.allow_stats) - return; + 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: @@ -2516,11 +2570,18 @@ void Reader::detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInf /// 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; + return false; if (column_info.idx_in_output_block >= sample_block_to_output_columns_idx.size()) - return; + 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; + 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; @@ -2589,20 +2650,102 @@ void Reader::detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInf ProfileEvents::increment(ProfileEvents::ParquetConstantColumnChunks); } +bool Reader::detectConstantSubchunk( + const ColumnChunk & column, const PrimitiveColumnInfo & column_info, + size_t start_row, size_t end_row, size_t row_group_num_rows, + bool & out_all_null, Field & out_value) const +{ + if (column.page_const_info.empty()) + return false; + const size_t num_pages = column.offset_index.page_locations.size(); + if (num_pages == 0 || column.page_const_info.size() != num_pages) + return false; + + bool any = false; + bool all_pages_null = true; + bool all_pages_const_same = true; + Field value; + bool value_set = false; + + for (size_t p = 0; p < num_pages; ++p) + { + const size_t p_start = static_cast(column.offset_index.page_locations[p].first_row_index); + const size_t p_end = (p + 1 < num_pages) + ? static_cast(column.offset_index.page_locations[p + 1].first_row_index) + : row_group_num_rows; + if (p_end <= start_row || p_start >= end_row) + continue; // page does not overlap the subgroup's row range + + any = true; + const auto & pci = column.page_const_info[p]; + if (!pci.all_null) + all_pages_null = false; + if (pci.is_const) + { + if (!value_set) + { + value = pci.value; + value_set = true; + } + else if (value != pci.value) + all_pages_const_same = false; + } + else + { + all_pages_const_same = false; + } + } + + if (!any) + return false; + + if (all_pages_null) + { + /// Every overlapping page is entirely null - mirror detectConstantColumn's all-null branch. + const bool null_as_default = options.format.null_as_default && !column_info.output_nullable; + if (column_info.output_nullable) + out_value = Null{}; + else if (null_as_default) + out_value = column_info.output_type->getDefault(); + else + return false; // non-nullable output without null substitution: let normal decode error + out_all_null = true; + return true; + } + + if (all_pages_const_same && value_set) + { + out_all_null = false; + out_value = value; + return true; + } + + return false; +} + void Reader::decodePrimitiveColumn(ColumnChunk & column, const PrimitiveColumnInfo & column_info, ColumnSubchunk & subchunk, const RowGroup & row_group, RowSubgroup & row_subgroup, MemoryUsageDiff & diff) { - if (column.is_constant) + /// 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) { - /// This chunk provably holds a single value in every row (see detectConstantColumn), and its - /// data pages were never fetched. Skip all decoding and hand the already-decoded value to - /// formOutputColumn, which materializes it directly in the final output type. The value is - /// in the output (post-cast) domain, so it must not go through the decoded_type column and - /// castColumn path. We still run the per-output-column bookkeeping below so the output column - /// is formed once the last of its primitive columns is done. subchunk.is_constant = true; subchunk.constant_value = column.constant_value; subchunk.is_all_null = column.is_all_null; + } + if (subchunk.is_constant) + { + /// This subchunk provably holds a single value in every row - either the whole chunk (tier 1, + /// detectConstantColumn; its data pages were never fetched) or just this subgroup's row range + /// (tier 2, detectConstantSubchunk; the pages are skipped forward by the next subgroup's + /// skipToRowOrNextPage). Skip decoding and hand the value to formOutputColumn, which + /// materializes it directly in the final output type. The value is in the output (post-cast) + /// domain, so it must not go through the decoded_type column and castColumn path. We still run + /// the per-output-column bookkeeping below so the output column is formed once the last of its + /// primitive columns is done. (The subchunk fields were set above for tier 1, or during + /// subgroup init for tier 2.) OutputColumnState & state = row_subgroup.output.at(column_info.idx_in_output_block); chassert(!state.column); size_t prev_count = state.primitive_columns_remaining.fetch_sub(1); diff --git a/src/Processors/Formats/Impl/Parquet/Reader.h b/src/Processors/Formats/Impl/Parquet/Reader.h index 4431c36cdfea3..05bc150b534e3 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.h +++ b/src/Processors/Formats/Impl/Parquet/Reader.h @@ -350,6 +350,19 @@ struct Reader /// records every row in block_missing_values (the plain constant case has no nulls). bool is_all_null = false; + /// Per-page constant info from the Column Index (tier 2; see applyColumnIndex and + /// detectConstantSubchunk). Populated only when the column index is loaded, indexed by data + /// page. `value` is in the output (post-cast) domain. Empty when unavailable. For truncatable + /// physical types (BYTE_ARRAY / FIXED_LEN_BYTE_ARRAY) only `all_null` is trusted, never + /// `is_const` (the Column Index has no per-page exactness flag). + struct PageConstInfo + { + bool is_const = false; /// page holds a single non-null value + bool all_null = false; /// page is entirely null + Field value; /// the value when is_const + }; + std::vector page_const_info; + /// Prefetches. /// TODO [parquet]: Check that all handles and tokens are reset after correct stages. PrefetchHandle bloom_filter_header_prefetch; @@ -646,6 +659,20 @@ struct Reader /// 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; + /// 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. From 1c770fac46a4519284f4c7c3ba5304baf141b775 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 19:11:10 +0300 Subject: [PATCH 06/20] Parquet v3: skip prefetch of constant subgroup pages [tier 2 phase 3] Completes tier-2: a per-subgroup constant column (detectConstantSubchunk) now also skips fetching its data pages, not just decoding them. In determinePagesToPrefetch, a constant subchunk claims no pages; a page fully inside it is released (never fetched), while a page shared with a neighbouring non-constant subgroup is left for that subgroup to claim. Safe because tier 2 only exists when the Column Index (hence Offset Index) is loaded: a constant subgroup never calls skipToRowOrNextPage, and a non-constant subgroup jumps directly via the offset index to its own claimed pages, so a released constant page between them is never accessed. The whole-chunk data_pages_prefetch is still split (likely_to_be_used=false), so only claimed pages are actually read. This turns the tier-2 CPU/memory win into an I/O win as well (fewer S3 GETs / ParquetPrefetcherReadRandomRead), matching tier 1 but at page granularity. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- src/Processors/Formats/Impl/Parquet/ReadManager.cpp | 2 +- src/Processors/Formats/Impl/Parquet/Reader.cpp | 11 ++++++++++- src/Processors/Formats/Impl/Parquet/Reader.h | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp index b85c225850081..0f0ef93d2813a 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), row_subgroup, row_group, prefetches); /// Side note: would be nice to avoid reading the dictionary if all dictionary-encoded /// pages were filtered out (e.g. if it's a 100 MB column chunk with unique long strings, diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 9a26a16944a93..9e6caab05ba97 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2412,7 +2412,7 @@ 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 RowSubgroup & row_subgroup, const RowGroup & row_group, std::vector & out) { chassert(row_subgroup.filter.rows_pass > 0); if (column.is_constant) @@ -2481,6 +2481,15 @@ 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; + if (passes_filter) out.push_back(&page.prefetch); // this subgroup needs this page else if (page.end_row_idx > subgroup_end) diff --git a/src/Processors/Formats/Impl/Parquet/Reader.h b/src/Processors/Formats/Impl/Parquet/Reader.h index 05bc150b534e3..214b834e585c3 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.h +++ b/src/Processors/Formats/Impl/Parquet/Reader.h @@ -644,7 +644,7 @@ 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 RowSubgroup & row_subgroup, const RowGroup & row_group, std::vector & out); /// Guess how much memory ColumnSubchunk::{column, arrays_offsets} will use, per row. double estimateColumnMemoryBytesPerRow(const ColumnChunk & column, const RowGroup & row_group, const PrimitiveColumnInfo & column_info) const; From 1f32c8f3d1d379b9ff31774ee827116187288177 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 19:24:42 +0300 Subject: [PATCH 07/20] Parquet v3: optional force-load of column index for constant detection Adds input_format_parquet_use_column_index_for_constant_columns (default off). By default tier-2 per-subgroup constant detection only runs where the Column Index is already loaded (columns with a predicate). This setting force-loads the Column Index (and Offset Index) for eligible read columns without a predicate, so tier-2 can skip single-valued page runs on them too - worthwhile for sorted / low-cardinality columns, at the cost of a small extra (tail-contiguous, coalesced) index read. A force-loaded column takes the same load path as a predicate column (use_column_index = true); applyColumnIndex records per-page constant info but skips page-level predicate pruning when the column has no condition (prev_row_idx stays 0 -> whole chunk selected -> no restriction). Setting is declared in FormatFactorySettings, plumbed through FormatSettings / FormatFactory, and recorded in SettingsChangesHistory (26.6). Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- .../parquet-v3-page-level-constant-column.md | 16 ++++++++++++++-- src/Core/FormatFactorySettings.h | 3 +++ src/Core/SettingsChangesHistory.cpp | 3 +++ src/Formats/FormatFactory.cpp | 1 + src/Formats/FormatSettings.h | 1 + src/Processors/Formats/Impl/Parquet/Reader.cpp | 18 +++++++++++++++--- 6 files changed, 37 insertions(+), 5 deletions(-) diff --git a/docs/design/parquet-v3-page-level-constant-column.md b/docs/design/parquet-v3-page-level-constant-column.md index 218490336f93e..36970a2effc73 100644 --- a/docs/design/parquet-v3-page-level-constant-column.md +++ b/docs/design/parquet-v3-page-level-constant-column.md @@ -56,11 +56,23 @@ page overlapping the subgroup's row range is constant with the *same* value (or - **Phase 5** — ProfileEvents comparison on clustered data: expect further `S3GetObject` / `ParquetFetchWaitTimeMicroseconds` drops with chunk count unchanged. +## Optional force-load + +By default tier 2 only uses the Column Index when it is already loaded (columns with a predicate +push-down). `input_format_parquet_use_column_index_for_constant_columns` (default off) extends it: +the Column Index (+ Offset Index) is force-loaded for eligible read columns that have no predicate, +so tier 2 can also fire on them. Cost is a small extra read of the (tiny, tail-contiguous, coalesced) +index; worthwhile mainly for sorted / low-cardinality columns. `applyColumnIndex` records per-page +constant info but skips predicate pruning when the column has no condition. A future `auto` mode +could gate this on footer signals (row-group `sorting_columns`, low compressed-bytes-per-value, +dictionary encoding stats) instead of an all-or-nothing switch. + ## Guardrails - Fixed-width numeric/date/time only (truncation). -- Reuse the Column Index only when already loaded; never force-fetch it just for this. -- Gate on the existing `input_format_parquet_use_constant_column_optimization` setting. +- 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`. - 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. diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 62425263254c3..3247aabe95d78 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -238,6 +238,9 @@ Minor tweak to how pages are read from parquet file when no page filtering is us )", 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. +)", 0) \ + DECLARE(Bool, input_format_parquet_use_column_index_for_constant_columns, false, R"( +Load the Parquet Column Index for read columns that have no predicate of their own, so the constant-column optimization can also skip data pages that are single-valued over a row subgroup (not just over a whole column chunk). Costs a small extra read of the (tiny) Column Index; only worthwhile when columns are sorted or low-cardinality. Applies only when `input_format_parquet_use_constant_column_optimization` is enabled. )", 0) \ DECLARE(Bool, input_format_parquet_verify_checksums, true, R"( Verify page checksums when reading parquet files. diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index 4830563f98c29..ed350c673bb7b 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -305,6 +305,9 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() { {"analyzer_compatibility_apply_final_to_all_joined_tables", true, false, "Fixed a bug in the analyzer where FINAL on the left-most table of a JOIN was incorrectly applied to the other joined tables as well. previous_value=true so `compatibility` with versions before 26.6 restores the old behavior."}, {"cloud_mode_database_engine", 1, 1, "Obsolete setting, the database engine in Cloud no longer depends on it."}, + {"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 (reader v3)."}, + {"input_format_parquet_prefetch_bandwidth_hide_seconds", 0, 0, "New setting: read back-pressure for the Parquet v3 reader; stop prefetching compressed data pages once in-flight compressed bytes exceed this many seconds of measured read throughput. 0 (the default and the pre-existing behavior) disables the back-pressure."}, + {"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 skip data pages that are single-valued over a row subgroup. Disabled by default (costs a small extra read)."}, {"analyzer_compatibility_allow_non_aggregate_in_having", false, false, "New compatibility setting. When enabled, the new analyzer mimics the legacy `HAVING`-to-`WHERE` rewrite for non-aggregate AND-conjuncts instead of raising `NOT_AN_AGGREGATE`."}, {"reserve_memory", 0, 0, "New setting to reserve memory for specific workload before starting a query."}, {"input_format_parquet_prefetch_memory_fraction", 0.6, 0.6, "New setting to tune the Parquet reader split of the column-data memory budget between compressed read-ahead and decode."}, diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index da10fef9b0bd9..a3ae7c24b3aed 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -232,6 +232,7 @@ FormatSettings getFormatSettings(const ContextPtr & context, const Settings & se 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.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 b8c7db0b5e166..1e801e0a5f575 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -387,6 +387,7 @@ struct FormatSettings 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 enable_json_parsing = true; bool preserve_order = false; diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 9e6caab05ba97..94c6fb8c1fd6f 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -1161,8 +1161,18 @@ void Reader::initializePrefetches() /// 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 && !column.is_constant && + 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( @@ -1172,7 +1182,7 @@ void Reader::initializePrefetches() /// Column index. column.use_column_index = !column.is_constant - && !primitive_columns[column_idx].column_index_conditions.empty() + && (!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) @@ -2028,7 +2038,9 @@ void Reader::applyColumnIndex(ColumnChunk & column, const PrimitiveColumnInfo & try { chassert(column.use_column_index); - chassert(!column_info.column_index_conditions.empty()); + /// column_index_conditions may be empty when the column index was force-loaded only for tier-2 + /// constant detection (input_format_parquet_use_column_index_for_constant_columns); in that + /// case we record per-page constant info below but do no page-level predicate pruning. auto data = prefetcher.getRangeData(column.column_index_prefetch); parq::ColumnIndex column_index; From 856e23f0889e003087d9e64cc7138d3757971074 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 19:57:33 +0300 Subject: [PATCH 08/20] Parquet v3: mixed-topology constant-page fill [experimental, default off] Approach B: when only PART of a row subgroup is single-valued (a constant run shorter than, or straddling, a subgroup), fill those pages from the per-page Column Index while decoding only the varying pages - producing a full column where whole-subgroup tier-2 cannot make a ColumnConst. Gated behind input_format_parquet_fill_constant_pages (default off). Additional gates keep it correct and simple: - output column must not need a post-decode cast (we fill the decoded_type column with the Column Index value, valid only when decoded == output value type); - no predicate on the column (so no page pruning; data_pages == all pages); - no prewhere filtering in the subgroup (avoids filter/range intersection); - at least one single-value page and no all-null page in the subgroup (all-null pages fall back to the standard decode). fillConstantPagesAndDecodeRest walks the subgroup page by page: a single-value page is filled via insertMany (+ null-map zeros) without reading it; a varying page is decoded with the existing skipToRowOrNextPage + readRowsInPage, which jumps over the filled pages via the offset index without loading them. First cut is decode-fill only: constant pages are still prefetched (correct, some wasted I/O). Skipping their prefetch needs cross-subgroup coordination and is a follow-up. Design: docs/design/parquet-v3-page-level-constant-column.md Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- src/Core/FormatFactorySettings.h | 3 + src/Core/SettingsChangesHistory.cpp | 1 + src/Formats/FormatFactory.cpp | 1 + src/Formats/FormatSettings.h | 1 + .../Formats/Impl/Parquet/Reader.cpp | 118 +++++++++++++++++- src/Processors/Formats/Impl/Parquet/Reader.h | 10 ++ 6 files changed, 133 insertions(+), 1 deletion(-) diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 3247aabe95d78..fd6afd6a78991 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -241,6 +241,9 @@ When a Parquet column chunk provably holds a single value in every row (accordin )", 0) \ DECLARE(Bool, input_format_parquet_use_column_index_for_constant_columns, false, R"( Load the Parquet Column Index for read columns that have no predicate of their own, so the constant-column optimization can also skip data pages that are single-valued over a row subgroup (not just over a whole column chunk). Costs a small extra read of the (tiny) Column Index; only worthwhile when columns are sorted or low-cardinality. Applies only when `input_format_parquet_use_constant_column_optimization` is enabled. +)", 0) \ + DECLARE(Bool, input_format_parquet_fill_constant_pages, false, R"( +Experimental. When a Parquet column is single-valued over some data pages but not the whole row subgroup, fill those pages' rows from the per-page Column Index statistics instead of reading and decoding them (mixed-topology subgroups). Extends the constant-column optimization below the subgroup granularity. Requires `input_format_parquet_use_constant_column_optimization`; disabled by default. )", 0) \ DECLARE(Bool, input_format_parquet_verify_checksums, true, R"( Verify page checksums when reading parquet files. diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index ed350c673bb7b..68a0da75c5b88 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -308,6 +308,7 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() {"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 (reader v3)."}, {"input_format_parquet_prefetch_bandwidth_hide_seconds", 0, 0, "New setting: read back-pressure for the Parquet v3 reader; stop prefetching compressed data pages once in-flight compressed bytes exceed this many seconds of measured read throughput. 0 (the default and the pre-existing behavior) disables the back-pressure."}, {"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 skip data pages that are single-valued over a row subgroup. Disabled by default (costs a small extra read)."}, + {"input_format_parquet_fill_constant_pages", false, false, "New experimental setting: fill single-valued Parquet data pages from per-page Column Index statistics instead of decoding them, even when only part of a row subgroup is constant. Disabled by default."}, {"analyzer_compatibility_allow_non_aggregate_in_having", false, false, "New compatibility setting. When enabled, the new analyzer mimics the legacy `HAVING`-to-`WHERE` rewrite for non-aggregate AND-conjuncts instead of raising `NOT_AN_AGGREGATE`."}, {"reserve_memory", 0, 0, "New setting to reserve memory for specific workload before starting a query."}, {"input_format_parquet_prefetch_memory_fraction", 0.6, 0.6, "New setting to tune the Parquet reader split of the column-data memory budget between compressed read-ahead and decode."}, diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index a3ae7c24b3aed..c50ad8ddf175a 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -233,6 +233,7 @@ FormatSettings getFormatSettings(const ContextPtr & context, const Settings & se 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 1e801e0a5f575..ab7d11ca09a91 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -388,6 +388,7 @@ struct FormatSettings 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/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 94c6fb8c1fd6f..23749cdba35cf 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2744,6 +2744,108 @@ bool Reader::detectConstantSubchunk( 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 + if (column_info.column_index_condition) + return false; // a predicate on this column may have pruned pages; keep the standard path + if (!constColumnMaterializationEligible(column_info)) + return false; + if (row_subgroup.filter.rows_pass != row_subgroup.filter.rows_total) + return false; // some rows filtered out in this subgroup; avoid filter/range intersection + + /// 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 single-value page and no all-null page overlapping the subgroup (all-null + /// pages are not handled by the fill; fall back to the standard decode for those subgroups). + 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_const = false; + for (size_t p = 0; p < num_pages; ++p) + { + const size_t p_start = size_t(pages[p].first_row_index); + const size_t p_end = (p + 1 < num_pages) ? size_t(pages[p + 1].first_row_index) : rg_rows; + if (p_end <= start || p_start >= end) + continue; + const auto & pci = column.page_const_info[p]; + if (pci.all_null) + return false; + if (pci.is_const) + any_const = true; + } + return any_const; +} + +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 end = start + 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); + + ColumnUInt8::Container * null_map_data = subchunk.null_map + ? &assert_cast(*subchunk.null_map).getData() + : nullptr; + + /// Position at the first page overlapping `start`. + size_t p = 0; + while (p < num_pages && (p + 1 < num_pages ? size_t(pages[p + 1].first_row_index) : rg_rows) <= start) + ++p; + + size_t row = start; + while (row < end) + { + chassert(p < num_pages); + const size_t p_end = (p + 1 < num_pages) ? size_t(pages[p + 1].first_row_index) : rg_rows; + const size_t seg_end = std::min(end, p_end); + chassert(seg_end > row); + const size_t count = seg_end - row; + const auto & pci = column.page_const_info[p]; + + if (pci.is_const) + { + /// Fill the single value without reading the page. Value is in the output value domain, + /// which equals decoded_type here (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 + { + /// Varying page: decode [row, seg_end) via the normal machinery. skipToRowOrNextPage jumps + /// to this page (via the offset index), stepping over any filled const pages without + /// loading them; readRowsInPage appends the decoded values (and null-map entries). + skipToRowOrNextPage(row, column, column_info); + readRowsInPage(seg_end, subchunk, column, column_info, &row_subgroup); + } + + row = seg_end; + if (row == p_end) + ++p; + } +} + 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 @@ -2813,6 +2915,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 @@ -2836,7 +2948,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); diff --git a/src/Processors/Formats/Impl/Parquet/Reader.h b/src/Processors/Formats/Impl/Parquet/Reader.h index 214b834e585c3..25312e228f178 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.h +++ b/src/Processors/Formats/Impl/Parquet/Reader.h @@ -673,6 +673,16 @@ struct Reader 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. From bfd6f7ae3867be0071d24a7c55edb62cfce8da50 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 20:01:41 +0300 Subject: [PATCH 09/20] Parquet v3: skip prefetch of filled constant pages (mixed topology) Completes the mixed-topology fill (input_format_parquet_fill_constant_pages, default off): a subgroup that fills its single-value pages from the Column Index no longer prefetches them. determinePagesToPrefetch consults willFillConstantPages (the same deterministic predicate the decode path uses) and, for a fill subgroup, does not claim its is_const pages - so a page overlapped only by fill subgroups is released and never read, while a page also decoded normally by another subgroup is still fetched. Also adds a no-prewhere / no-row-level-filter gate to willFillConstantPages so rows_pass == rows_total holds identically at prefetch time and decode time, keeping the two decisions consistent. This turns the mixed-topology fill from a decode-CPU-only win into an I/O win too (fewer page reads), matching tier-2 at sub-subgroup granularity. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- .../parquet-v3-page-level-constant-column.md | 13 +++++++++---- .../Formats/Impl/Parquet/ReadManager.cpp | 2 +- .../Formats/Impl/Parquet/Reader.cpp | 19 ++++++++++++++++++- src/Processors/Formats/Impl/Parquet/Reader.h | 2 +- 4 files changed, 29 insertions(+), 7 deletions(-) diff --git a/docs/design/parquet-v3-page-level-constant-column.md b/docs/design/parquet-v3-page-level-constant-column.md index 36970a2effc73..bbc16efdb6703 100644 --- a/docs/design/parquet-v3-page-level-constant-column.md +++ b/docs/design/parquet-v3-page-level-constant-column.md @@ -76,7 +76,12 @@ dictionary encoding stats) instead of an all-or-nothing switch. - 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. -## Out of scope - -In-subgroup partial fill for constant runs *shorter* than a subgroup (skip only those pages' bytes, -yield a full column) — a later follow-up. +## 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). Gated to: no cast on the output value, no predicate on the +column, no prewhere/row-level filter, and no all-null pages in the subgroup. Experimental, off by +default; needs a build + correctness tests before it can be trusted. diff --git a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp index 0f0ef93d2813a..d15cd422a7694 100644 --- a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp +++ b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp @@ -772,7 +772,7 @@ void ReadManager::scheduleTask(Task task, bool is_first_in_group, MemoryUsageDif /// Queue this subgroup's data-page reads; startPrefetch (below) issues them and charges /// compressed bytes to the ColumnDataPrefetch budget, separate from the decode budget, /// so many row groups prefetch ahead while only a few decode at once. - reader.determinePagesToPrefetch(column, row_subgroup.columns.at(task.column_idx), row_subgroup, row_group, prefetches); + reader.determinePagesToPrefetch(column, row_subgroup.columns.at(task.column_idx), reader.primitive_columns.at(task.column_idx), row_subgroup, row_group, prefetches); /// Side note: would be nice to avoid reading the dictionary if all dictionary-encoded /// pages were filtered out (e.g. if it's a 100 MB column chunk with unique long strings, diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 23749cdba35cf..90f6e0544f0ef 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2424,7 +2424,7 @@ void Reader::decodeOffsetIndex(ColumnChunk & column, const RowGroup & row_group) } } -void Reader::determinePagesToPrefetch(ColumnChunk & column, const ColumnSubchunk & subchunk, 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) @@ -2432,6 +2432,12 @@ void Reader::determinePagesToPrefetch(ColumnChunk & column, const ColumnSubchunk 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; @@ -2502,6 +2508,15 @@ void Reader::determinePagesToPrefetch(ColumnChunk & column, const ColumnSubchunk 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) + passes_filter = false; + } + if (passes_filter) out.push_back(&page.prefetch); // this subgroup needs this page else if (page.end_row_idx > subgroup_end) @@ -2756,6 +2771,8 @@ bool Reader::willFillConstantPages( return false; // no Column Index info retained if (column_info.column_index_condition) return false; // a predicate on this column may have pruned pages; keep the standard path + if (format_filter_info && (format_filter_info->prewhere_info || format_filter_info->row_level_filter)) + return false; // a prewhere/row-level filter would make rows_pass < rows_total at decode time if (!constColumnMaterializationEligible(column_info)) return false; if (row_subgroup.filter.rows_pass != row_subgroup.filter.rows_total) diff --git a/src/Processors/Formats/Impl/Parquet/Reader.h b/src/Processors/Formats/Impl/Parquet/Reader.h index 25312e228f178..6325e3d8acd01 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.h +++ b/src/Processors/Formats/Impl/Parquet/Reader.h @@ -644,7 +644,7 @@ 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 ColumnSubchunk & subchunk, const RowSubgroup & row_subgroup, const RowGroup & row_group, std::vector & out); + void determinePagesToPrefetch(ColumnChunk & column, const ColumnSubchunk & subchunk, const PrimitiveColumnInfo & column_info, const RowSubgroup & row_subgroup, const RowGroup & row_group, std::vector & out); /// Guess how much memory ColumnSubchunk::{column, arrays_offsets} will use, per row. double estimateColumnMemoryBytesPerRow(const ColumnChunk & column, const RowGroup & row_group, const PrimitiveColumnInfo & column_info) const; From c173818693bc56d7dc0748451926fd1438f784c5 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 20:23:09 +0300 Subject: [PATCH 10/20] Parquet v3: allow string constants (drop min==max truncation guard) min_value == max_value provably means a single exact value for every physical type, including BYTE_ARRAY / FIXED_LEN_BYTE_ARRAY. Statistics and Column Index bounds are always valid (min_value <= every value <= max_value) and truncation only ever widens them, so a truncated value - or any page/chunk with two distinct values - yields min_value < max_value. Equality therefore requires a single value short enough to be stored exactly; the is_*_value_exact flags are implied and, for the Column Index (which has no per-page exact flag), never needed. Remove the BYTE_ARRAY/FIXED_LEN exclusion from tier 1 (detectConstantColumn) and the per-page recording in tier 2 (applyColumnIndex), so constant string columns and string constant page runs get the optimization too. Also fixes tier 1 for writers that omit is_*_value_exact (previously any such BYTE_ARRAY constant was skipped even when short and exact). Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- .../parquet-v3-page-level-constant-column.md | 6 ++++- .../Formats/Impl/Parquet/Reader.cpp | 25 ++++++++----------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/docs/design/parquet-v3-page-level-constant-column.md b/docs/design/parquet-v3-page-level-constant-column.md index bbc16efdb6703..352e31e6822aa 100644 --- a/docs/design/parquet-v3-page-level-constant-column.md +++ b/docs/design/parquet-v3-page-level-constant-column.md @@ -69,7 +69,11 @@ dictionary encoding stats) instead of an all-or-nothing switch. ## Guardrails -- Fixed-width numeric/date/time only (truncation). +- All types, including `BYTE_ARRAY` / `FIXED_LEN_BYTE_ARRAY` strings. No truncation guard is needed + for the `min == max` case: statistics/Column-Index bounds are always valid + (`min <= every value <= max`) and truncation only widens them, so `min == max` proves a single + exact value (a truncated or multi-valued page yields `min < max`). This holds at both the chunk + level (tier 1) and per page (tier 2), so neither needs the `is_*_value_exact` flag. - Gate on the existing `input_format_parquet_use_constant_column_optimization` setting; the force-load above is additionally gated by `input_format_parquet_use_column_index_for_constant_columns`. diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 90f6e0544f0ef..f5d1353b4e14a 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2060,13 +2060,12 @@ void Reader::applyColumnIndex(ColumnChunk & column, const PrimitiveColumnInfo & /// 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). For truncatable physical types the Column Index has no per-page - /// exactness flag, so a per-page min == max is untrustworthy: record only `all_null` there. + /// 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; - const bool may_be_truncated = - column.meta->meta_data.type == parq::Type::BYTE_ARRAY - || column.meta->meta_data.type == parq::Type::FIXED_LEN_BYTE_ARRAY; if (record_page_const) column.page_const_info.assign(num_pages, ColumnChunk::PageConstInfo{}); @@ -2100,7 +2099,7 @@ void Reader::applyColumnIndex(ColumnChunk & column, const PrimitiveColumnInfo & /// 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 && !may_be_truncated && !can_be_null + if (record_page_const && !can_be_null && !range.left.isNull() && range.left == range.right) { column.page_const_info[page_idx].is_const = true; @@ -2665,15 +2664,11 @@ void Reader::detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInf if (stats.min_value != stats.max_value) return; - /// For BYTE_ARRAY / FIXED_LEN_BYTE_ARRAY the writer may store truncated min/max, which could make - /// two different values compare equal. Trust min == max only when the writer marked both exact. - /// Fixed-width numeric types are never truncated, so min == max is always exact for them. - const bool may_be_truncated = - meta_data.type == parq::Type::BYTE_ARRAY || meta_data.type == parq::Type::FIXED_LEN_BYTE_ARRAY; - if (may_be_truncated - && !(stats.__isset.is_min_value_exact && stats.is_min_value_exact - && stats.__isset.is_max_value_exact && stats.is_max_value_exact)) - 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; column_info.decoder.decodeField(stats.min_value, /*is_max=*/ false, value); From 25b664a242a1226b282cb0f97736604e329f257c Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 20:33:57 +0300 Subject: [PATCH 11/20] Parquet v3: handle all-null pages in mixed-topology fill (lift gate 1) Previously a mixed-topology subgroup (input_format_parquet_fill_constant_pages) bailed to normal decode if any overlapping page was all-null. Now fill them too: an all-null page appends no non-null values and marks its rows null in the null map; the existing expand() + Nullable-wrap / null_as_default tail finalizes them exactly as the normal decode does (the column holds compact non-null values, the null map covers all rows). determinePagesToPrefetch also skips prefetching all-null pages, matching the fill. willFillConstantPages now accepts all-null pages as fillable, but still bails when an all-null page is present and the output can represent neither null (non-Nullable output) nor a default (no null_as_default) - the standard decode raises the usual not-null error there. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- .../parquet-v3-page-level-constant-column.md | 6 ++-- .../Formats/Impl/Parquet/Reader.cpp | 29 ++++++++++++++----- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/docs/design/parquet-v3-page-level-constant-column.md b/docs/design/parquet-v3-page-level-constant-column.md index 352e31e6822aa..bd8bccb527823 100644 --- a/docs/design/parquet-v3-page-level-constant-column.md +++ b/docs/design/parquet-v3-page-level-constant-column.md @@ -87,5 +87,7 @@ subgroup: `fillConstantPagesAndDecodeRest` fills single-value pages from the Col 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). Gated to: no cast on the output value, no predicate on the -column, no prewhere/row-level filter, and no all-null pages in the subgroup. Experimental, off by -default; needs a build + correctness tests before it can be trusted. +column, no prewhere/row-level filter. All-null pages are handled (filled with nulls via the compact +values + null map + `expand` path, or the output default under `null_as_default`); a subgroup with +an all-null page only falls back when the output can represent neither null nor a default. +Experimental, off by default; needs a build + correctness tests before it can be trusted. diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index f5d1353b4e14a..b9ddcff38df7a 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2512,7 +2512,8 @@ void Reader::determinePagesToPrefetch(ColumnChunk & column, const ColumnSubchunk 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) + if (gid < column.page_const_info.size() + && (column.page_const_info[gid].is_const || column.page_const_info[gid].all_null)) passes_filter = false; } @@ -2784,12 +2785,15 @@ bool Reader::willFillConstantPages( if (num_pages == 0 || column.page_const_info.size() != num_pages) return false; - /// Require at least one single-value page and no all-null page overlapping the subgroup (all-null - /// pages are not handled by the fill; fall back to the standard decode for those subgroups). + /// 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_const = false; + 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); @@ -2797,12 +2801,12 @@ bool Reader::willFillConstantPages( if (p_end <= start || p_start >= end) continue; const auto & pci = column.page_const_info[p]; - if (pci.all_null) + if (pci.all_null && !nulls_representable) return false; - if (pci.is_const) - any_const = true; + if (pci.is_const || pci.all_null) + any_fillable = true; } - return any_const; + return any_fillable; } void Reader::fillConstantPagesAndDecodeRest( @@ -2843,6 +2847,15 @@ void Reader::fillConstantPagesAndDecodeRest( if (null_map_data) null_map_data->resize_fill(null_map_data->size() + count, 0); } + else if (pci.all_null) + { + /// All-null page: append no non-null values (the column holds the compact non-null + /// values); mark every row null. The caller's tail expand()s defaults into these + /// positions and applies the Nullable wrap / null_as_default handling, exactly as the + /// normal decode does. null_map exists here (an all-null page implies need_null_map). + chassert(null_map_data); + null_map_data->resize_fill(null_map_data->size() + count, 1); + } else { /// Varying page: decode [row, seg_end) via the normal machinery. skipToRowOrNextPage jumps From 85373042b950218c1c68c830c8f178127c32d3b0 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 20:43:28 +0300 Subject: [PATCH 12/20] Parquet v3: allow page-pruned columns in mixed fill (lift gate 3) Drop the column_index_condition gate from willFillConstantPages. A page-pruning predicate on the column (column_index_condition) is safe for the fill: subgroups are built only over contiguous surviving row ranges, so a pruned page never overlaps a subgroup and the fill never walks it; the prefetch-skip indexes page_const_info by each page global position (page.meta into page_locations), which is correct regardless of the data_pages subset. A column carrying an actual prewhere/row-level filter is still blocked by the no-prewhere gate. Gate 2 (output needs_cast) is intentionally left in place: whether decodeField yields the decoded or the output value domain is ambiguous from static reading (SchemaConverter/convertField vs the tier-1 is_constant branch), and guessing wrong is silent wrong data. It needs a build + a needs_cast test to resolve (and that test would also confirm tier-1/tier-2 on hint-cast columns). Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- src/Processors/Formats/Impl/Parquet/Reader.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index b9ddcff38df7a..64fa93903a02c 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2765,10 +2765,11 @@ bool Reader::willFillConstantPages( return false; // whole chunk already constant (tier 1) if (column.page_const_info.empty()) return false; // no Column Index info retained - if (column_info.column_index_condition) - return false; // a predicate on this column may have pruned pages; keep the standard path if (format_filter_info && (format_filter_info->prewhere_info || format_filter_info->row_level_filter)) return false; // a prewhere/row-level filter would make rows_pass < rows_total at decode time + /// A page-pruning predicate on this column (column_index_condition without prewhere) is fine: + /// pruned pages fall outside every subgroup's contiguous surviving row range, so the fill never + /// walks them, and the prefetch-skip indexes page_const_info by each page's global position. if (!constColumnMaterializationEligible(column_info)) return false; if (row_subgroup.filter.rows_pass != row_subgroup.filter.rows_total) From b9c0a89be5c2a6e65f67caccb3e4dd9912a19777 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 21:11:47 +0300 Subject: [PATCH 13/20] Parquet v3: filter-aware mixed fill under prewhere (lift gate 4) The mixed-topology fill now walks the rows that pass the filter (row_subgroup.filter) instead of the whole subgroup range, so it works under PREWHERE / row-level filters: it iterates passing ranges (like the standard row-range decode) and, within each, fills constant / all-null pages for their overlapping passing rows and decodes varying pages for the contiguous passing sub-range. It therefore produces exactly rows_pass values for any filter, and willFillConstantPages no longer depends on rows_pass - so the decision is identical at prefetch time and decode time and the prefetch-skip can never drop a page the decode needs. Removes the no-prewhere and rows_pass == rows_total gates from willFillConstantPages. The only remaining gate is needs_cast (build-gated; see the decodeField value-domain question). Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- .../parquet-v3-page-level-constant-column.md | 15 ++- .../Formats/Impl/Parquet/Reader.cpp | 114 ++++++++++-------- 2 files changed, 76 insertions(+), 53 deletions(-) diff --git a/docs/design/parquet-v3-page-level-constant-column.md b/docs/design/parquet-v3-page-level-constant-column.md index bd8bccb527823..83887eaa029c4 100644 --- a/docs/design/parquet-v3-page-level-constant-column.md +++ b/docs/design/parquet-v3-page-level-constant-column.md @@ -86,8 +86,13 @@ dictionary encoding stats) instead of an all-or-nothing switch. 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). Gated to: no cast on the output value, no predicate on the -column, no prewhere/row-level filter. All-null pages are handled (filled with nulls via the compact -values + null map + `expand` path, or the output default under `null_as_default`); a subgroup with -an all-null page only falls back when the output can represent neither null nor a default. -Experimental, off by default; needs a build + correctness tests before it can be trusted. +deterministic so both paths agree). The fill walks the rows that pass the filter (`row_subgroup.filter`), so it works under PREWHERE / +row-level filters and page-pruning predicates too - it produces exactly `rows_pass` values for any +filter, and because the decision no longer depends on `rows_pass` it is identical at prefetch time +and decode time (so the prefetch-skip can never drop a page the decode needs). All-null pages are +filled (nulls via the compact values + null map + `expand` path, or the output default under +`null_as_default`); a subgroup with an all-null page falls back only when the output can represent +neither null nor a default. The one remaining gate is `needs_cast`: the fill writes the Column Index +value into the `decoded_type` column, valid only when no post-decode cast applies (resolving whether +`decodeField` yields the decoded or the output value domain is build-gated). Experimental, off by +default; needs a build + correctness tests before it can be trusted. diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 64fa93903a02c..8b3dd31c5c7b1 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2765,15 +2765,12 @@ bool Reader::willFillConstantPages( return false; // whole chunk already constant (tier 1) if (column.page_const_info.empty()) return false; // no Column Index info retained - if (format_filter_info && (format_filter_info->prewhere_info || format_filter_info->row_level_filter)) - return false; // a prewhere/row-level filter would make rows_pass < rows_total at decode time - /// A page-pruning predicate on this column (column_index_condition without prewhere) is fine: - /// pruned pages fall outside every subgroup's contiguous surviving row range, so the fill never - /// walks them, and the prefetch-skip indexes page_const_info by each page's global position. + /// 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; - if (row_subgroup.filter.rows_pass != row_subgroup.filter.rows_total) - return false; // some rows filtered out in this subgroup; avoid filter/range intersection /// 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). @@ -2815,60 +2812,81 @@ void Reader::fillConstantPagesAndDecodeRest( ColumnSubchunk & subchunk, const RowGroup & row_group, RowSubgroup & row_subgroup) { const size_t start = row_subgroup.start_row_idx; - const size_t end = start + row_subgroup.filter.rows_total; + 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; - /// Position at the first page overlapping `start`. - size_t p = 0; - while (p < num_pages && (p + 1 < num_pages ? size_t(pages[p + 1].first_row_index) : rg_rows) <= start) - ++p; + auto page_end_of = [&](size_t pg) { return (pg + 1 < num_pages) ? size_t(pages[pg + 1].first_row_index) : rg_rows; }; - size_t row = start; - while (row < end) + /// 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) { - chassert(p < num_pages); - const size_t p_end = (p + 1 < num_pages) ? size_t(pages[p + 1].first_row_index) : rg_rows; - const size_t seg_end = std::min(end, p_end); - chassert(seg_end > row); - const size_t count = seg_end - row; - const auto & pci = column.page_const_info[p]; - - if (pci.is_const) - { - /// Fill the single value without reading the page. Value is in the output value domain, - /// which equals decoded_type here (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: append no non-null values (the column holds the compact non-null - /// values); mark every row null. The caller's tail expand()s defaults into these - /// positions and applies the Nullable wrap / null_as_default handling, exactly as the - /// normal decode does. null_map exists here (an all-null page implies need_null_map). - chassert(null_map_data); - null_map_data->resize_fill(null_map_data->size() + count, 1); - } - else + size_t num_rows = rows_total - row_subidx; + if (!filter.empty()) { - /// Varying page: decode [row, seg_end) via the normal machinery. skipToRowOrNextPage jumps - /// to this page (via the offset index), stepping over any filled const pages without - /// loading them; readRowsInPage appends the decoded values (and null-map entries). - skipToRowOrNextPage(row, column, column_info); - readRowsInPage(seg_end, subchunk, column, column_info, &row_subgroup); + while (row_subidx < rows_total && !filter[row_subidx]) + ++row_subidx; + num_rows = 0; + while (row_subidx + num_rows < rows_total && filter[row_subidx + num_rows]) + ++num_rows; } + if (!num_rows) + break; + const size_t range_start = start + row_subidx; + const size_t range_end = range_start + num_rows; + row_subidx += num_rows; + + size_t row = range_start; + while (row < range_end) + { + while (page_cursor < num_pages && page_end_of(page_cursor) <= row) + ++page_cursor; + chassert(page_cursor < num_pages); + const size_t seg_end = std::min(range_end, page_end_of(page_cursor)); + chassert(seg_end > row); + const size_t count = seg_end - row; + const auto & pci = column.page_const_info[page_cursor]; + + if (pci.is_const) + { + /// Fill the single value without reading the page (value is in decoded_type domain, + /// which equals the output value domain - willFillConstantPages required no cast). A + /// single-value page has no nulls, so any null map gets zeros for these rows. + subchunk.column->insertMany(pci.value, count); + if (null_map_data) + null_map_data->resize_fill(null_map_data->size() + count, 0); + } + else if (pci.all_null) + { + /// All-null page: no non-null values; mark these rows null (expand() fills defaults + /// later). null_map exists here (an all-null page implies need_null_map). + chassert(null_map_data); + null_map_data->resize_fill(null_map_data->size() + count, 1); + } + else + { + /// Varying page: decode the contiguous passing sub-range [row, seg_end). All rows in + /// it pass, so no per-row filter is applied here. skipToRowOrNextPage jumps to the page + /// via the offset index, stepping over filled const/all-null pages without loading them. + skipToRowOrNextPage(row, column, column_info); + readRowsInPage(seg_end, subchunk, column, column_info, /*row_subgroup=*/ nullptr); + } - row = seg_end; - if (row == p_end) - ++p; + row = seg_end; + } } } From 634300e1b80e3e7fe120d0c8d3db0a96bfee462e Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 21:53:27 +0300 Subject: [PATCH 14/20] Parquet v3: cast the materialized constant (future-proof needs_cast) formOutputColumn now builds the single-value constant in input_type and applies the same castColumn the per-row decode uses when needs_cast is set, instead of inserting the value straight into an output_type column and skipping the cast. Today this is a no-op: the optimization only fires when the stats decoder needs no value-transforming conversion (SchemaConverter gates allow_stats on that), so input_type == output_type for every constant column. The change keeps the constant path correct if allow_stats is ever generalized to allow transforming casts (e.g. decimal rescale) - the constant would then go through the same cast as the normal decode. Casting a ColumnConst is O(1) (one value) and preserves const-ness, so no cost. The all-null constant is synthesized in the output domain (Null / output default) and is not cast. The mixed fill already casts via the normal path, so it is future-safe too. The allow_stats / SchemaConverter logic is untouched. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- .../parquet-v3-page-level-constant-column.md | 12 +++++ .../Formats/Impl/Parquet/Reader.cpp | 47 +++++++++++++------ 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/docs/design/parquet-v3-page-level-constant-column.md b/docs/design/parquet-v3-page-level-constant-column.md index 83887eaa029c4..80bb8c2de78da 100644 --- a/docs/design/parquet-v3-page-level-constant-column.md +++ b/docs/design/parquet-v3-page-level-constant-column.md @@ -67,6 +67,18 @@ constant info but skips predicate pruning when the column has no condition. A fu could gate this on footer signals (row-group `sorting_columns`, low compressed-bytes-per-value, dictionary encoding stats) instead of an all-or-nothing switch. +## Cast safety (future-proofing) + +The optimization only fires when the stats decoder needs no value-transforming conversion +(`SchemaConverter` sets `allow_stats` accordingly), so today `input_type == output_type` for every +constant column and no cast is applied. To keep the constant path correct if `allow_stats` is ever +generalized to allow transforming casts, `formOutputColumn` builds the single-value constant in +`input_type` and runs the same `castColumn` the per-row decode uses when `needs_cast` is set - a +no-op today, O(1) on the `ColumnConst`, and it preserves const-ness. The all-null constant is +synthesized directly in the output domain (Null / output default), so it is not cast. The mixed fill +already goes through the normal `formOutputColumn` cast, so it is future-safe too. This does not +touch the `allow_stats` decision itself. + ## Guardrails - All types, including `BYTE_ARRAY` / `FIXED_LEN_BYTE_ARRAY` strings. No truncation guard is needed diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 8b3dd31c5c7b1..e558b42dadf5b 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -3822,20 +3822,39 @@ MutableColumnPtr Reader::formOutputColumn(RowSubgroup & row_subgroup, size_t out /// 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. The value is already in the output - /// (post-cast) domain, so we skip the decoded_type column and the castColumn below. - MutableColumnPtr single_value = output_info.output_type->createColumn(); - single_value->insert(subchunk.constant_value); - - /// An all-null chunk must record every row in block_missing_values, matching the normal - /// decode path (which records nulls from the null map); needed for - /// input_format_null_as_default. The single-value case has no nulls, so records nothing. - if (subchunk.is_all_null - && 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); - - return ColumnConst::create(std::move(single_value), num_rows); + /// aggregation over this column get a const key. + ColumnPtr result; + if (subchunk.is_all_null) + { + /// constant_value was synthesized directly in the output domain (Null for a Nullable + /// output, or the output default under null_as_default), so no cast applies. + MutableColumnPtr single_value = output_info.output_type->createColumn(); + single_value->insert(subchunk.constant_value); + result = ColumnConst::create(std::move(single_value), num_rows); + + /// An all-null chunk must record every row in block_missing_values, matching the + /// normal decode path (which records nulls from the null map); needed for + /// input_format_null_as_default. + if (output_info.idx_in_output_block.has_value() + && *output_info.idx_in_output_block < row_subgroup.block_missing_values.getNumColumns()) + row_subgroup.block_missing_values.setBits(*output_info.idx_in_output_block, num_rows); + } + else + { + /// The value came from decodeField, i.e. the decoded/input domain. Build the const in + /// input_type and apply the same castColumn the per-row decode uses when the output + /// type differs. Today the optimization only fires when the stats decoder does not + /// need a value-transforming conversion (input_type == output_type), so this cast is a + /// no-op; it is here so the constant path stays correct if that ever changes. Casting a + /// ColumnConst is O(1) (one value) and preserves const-ness. + MutableColumnPtr single_value = output_info.input_type->createColumn(); + single_value->insert(subchunk.constant_value); + result = ColumnConst::create(std::move(single_value), num_rows); + if (output_info.needs_cast) + result = castColumn({result, output_info.input_type, output_info.name}, output_info.output_type); + } + + return IColumn::mutate(std::move(result)); } res = std::move(subchunk.column); From 5ba632fbce5aedaba39dc05b79d8fab5164e9b3b Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Fri, 7 Aug 2026 23:12:04 +0300 Subject: [PATCH 15/20] Parquet v3: fix tier-2 constant detection for non-nullable columns Tier-2 per-subgroup constant detection (`detectConstantSubchunk`, gated by `input_format_parquet_use_column_index_for_constant_columns`) never fired for required (non-nullable) columns. `applyColumnIndex` computed `can_be_null` purely from the Column Index `null_counts`: `!__isset.null_counts || null_counts[page] != 0`. ClickHouse's own Parquet writer emits `null_counts` only for nullable columns (`Write.cpp`, `has_null_count = max_def == 1 && max_rep == 0`), so for a required column `null_counts` is absent and `can_be_null` was spuriously `true` on every page. That disabled the per-page `is_const` branch, so `page_const_info` was never populated and tier-2 detection never triggered - exactly for the common case of a non-nullable constant column. A required column (max def level 0) can never contain nulls regardless of whether the Column Index carries `null_counts`, so fold the schema `nullable` flag into `can_be_null`. `adjustRangeFromIndexIfNeeded` already gates its own use on `nullable && can_be_null`, so required-column predicate-pruning behavior is unchanged. Verified on a real build (sha 60841f9decd): an otherwise identical file with a nullable `run` column yields `ParquetConstantColumnSubchunks = 22` while the non-nullable variant yielded 0; this is the same null_count-omission pattern already fixed for tier-1 whole-chunk detection. Signed-off-by: UnamedRus --- src/Processors/Formats/Impl/Parquet/Reader.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index e558b42dadf5b..89dbe7e787a01 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2078,7 +2078,12 @@ void Reader::applyColumnIndex(ColumnChunk & column, const PrimitiveColumnInfo & range = Range::createWholeUniverse(); bool always_null = !column_index.null_pages.empty() && column_index.null_pages[page_idx]; - bool can_be_null = !column_index.__isset.null_counts || column_index.null_counts[page_idx] != 0; + /// A required column (max def level 0) can never contain nulls, regardless of whether the + /// Column Index carries null_counts. This matters for tier-2 constant detection below: + /// ClickHouse's own writer only emits null_counts for nullable columns (see Write.cpp, + /// has_null_count = max_def == 1), so without the `nullable` guard can_be_null would be + /// spuriously true for every required column and the is_const branch would never fire. + bool can_be_null = nullable && (!column_index.__isset.null_counts || column_index.null_counts[page_idx] != 0); if (record_page_const) column.page_const_info[page_idx].all_null = always_null; From 26e75a1bb8c22fd0e0bcf29d0b5ff4e14237d455 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Mon, 30 Nov 2026 13:30:49 +0100 Subject: [PATCH 16/20] Parquet v3: record constant-column settings in the settings history The cherry-picked constant-column commits carried a settings history hunk from the antalya-26.6 line, which added an unrelated `26.8` block and the back-pressure setting. Restore the file from `antalya-26.8` and record only the constant-column settings, in the current `26.8.39.20001.altinityantalya` block. Co-authored-by: Cursor --- src/Core/SettingsChangesHistory.cpp | 35 +++-------------------------- 1 file changed, 3 insertions(+), 32 deletions(-) diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index 68a0da75c5b88..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", { @@ -133,19 +136,6 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() {"throw_on_hive_partitioning_resolution_failure", false, true, "New setting to fail the query when Hive-style partitioning detection for an object storage table cannot list the storage, instead of running without the Hive partition columns."}, {"enable_json_ast_dialect", false, false, "New setting to enable the `clickhouse_json` value of the `dialect` setting, which interprets queries as JSON ASTs (the output of `parseQueryToJSON`) instead of SQL text."}, {"allow_metadata_only_named_tuple_alter", false, false, "New setting to control metadata-only ALTER for named Tuple subfield additions."}, - addSettingsChanges(settings_changes_history, "26.8", - { - {"max_insert_threads", 1, 0, "Changed the default from 1 (no parallel execution) to auto (0), which resolves to the number of CPU cores available to the server, reduced under memory pressure via `max_insert_threads_min_free_memory_per_thread`. This parallelizes `INSERT SELECT` by default. Set to 1 to restore the previous single-threaded behavior."}, - {"unique_key_probe_implementation", "auto", "auto", "New setting: selects the UNIQUE KEY probe implementation (currently only the simple baseline exists)"}, - {"s3_base", "", "", "New setting to specify the base URL for resolving relative URLs in the s3 table function and the S3 table engine."}, - {"use_query_condition_cache_for_top_k", false, false, "New setting to gate the query condition cache for `ORDER BY ... LIMIT n` (TopK) reads; disabled by default."}, - {"use_projection_index_in_read_pools", false, false, "New setting to drop mark ranges fully filtered out by a projection index before read tasks are created in MergeTree read pools."}, - {"allow_distinct_partitions_independently", false, true, "New setting to enable independent per-partition evaluation of `DISTINCT` when the partition expression is a deterministic function of the `DISTINCT` columns."}, - {"force_distinct_partitions_independently", false, false, "New setting to force independent per-partition evaluation of `DISTINCT` even when the cost heuristic would skip it."}, - {"max_number_of_partitions_for_independent_distinct", 128, 128, "New setting: maximal number of partitions to apply independent per-partition `DISTINCT`."}, - {"allow_lossy_numeric_supertype", false, false, "New setting that lets if/multiIf/coalesce/ifNull/array/map resolve all-numeric branches with no lossless common type (e.g. Decimal + Float64) to a numeric supertype (Float64, with possible precision loss), so the result can be aggregated. Independent of use_variant_as_common_type: with it off such branches previously raised NO_COMMON_TYPE, with it on they became a Variant; either way they now resolve to Float64."}, - {"throw_on_hive_partitioning_resolution_failure", false, true, "New setting to fail the query when Hive-style partitioning detection for an object storage table cannot list the storage, instead of running without the Hive partition columns."}, - {"allow_experimental_json_ast_dialect", false, false, "New setting to enable the `clickhouse_json` value of the `dialect` setting, which interprets queries as JSON ASTs (the output of `parseQueryToJSON`) instead of SQL text."}, {"analyzer_compatibility_apply_final_to_all_joined_tables", false, false, "New setting on master (default false = the fixed behavior). The behavior flip itself is recorded under 26.6, and the introduction for backports to older release branches (with default true) under 26.4."}, {"enable_parallel_single_level_merge", false, true, "New setting to parallelize the final merge of the single-level aggregation hash tables by splitting the key space into disjoint hash partitions that the threads merge independently."}, {"ai_function_text_default_credentials", "", "", "New setting"}, @@ -180,9 +170,6 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() {"input_format_json_max_object_size", 512 * 1024 * 1024, 512 * 1024 * 1024, "New setting to limit the maximum size of a single JSON object in bytes"}, {"format_hive_text_rows_delimiter", "\n", "\n", "New setting for the delimiter at the end of each row in the HiveText output format."}, {"output_format_parquet_wide_integer_as_decimal", false, false, "New setting to write `Int128`, `UInt128`, `Int256`, and `UInt256` values as standard Parquet `DECIMAL` values. The previous value keeps the legacy little-endian `FIXED_LEN_BYTE_ARRAY` representation."}, - {"ai_function_allow_insecure_endpoint", true, false, "AI functions now reject insecure (http) endpoints to remote hosts by default."}, - {"ai_function_max_api_calls_per_query", 0, 1000, "Bound outbound AI function HTTP calls per query by default (previously 0 - unlimited)."}, - {"join_runtime_filter_min_probe_rows", 0, 1000, "New setting to control minimum probe side size for installing JOIN runtime filters. It wasn't limited before, so previous value is 0 meaning always install."}, {"optimize_trivial_count_with_sparsity_filter", false, true, "Promote to BETA and enable by default: serve `SELECT count() FROM t WHERE ` from the persisted per-column `num_defaults` / `num_rows` counters when `` partitions rows into defaults vs non-defaults. Requires the MergeTree setting `compute_exact_num_defaults_for_sparse_columns` (also enabled by default now)."}, {"input_format_parquet_dictionary_filter_push_down", 0, 1024 * 1024, "New setting enabling Parquet row-group pruning based on dictionary page contents (reader v3). The value is the maximum dictionary page size in bytes for which the optimization applies; 0 (the previous behavior) disables it."}, {"input_format_read_datetime_number_as_raw_value", true, false, "From 26.8, an unquoted number for a `DateTime`/`DateTime64` column in the `JSON` and `Values`/`Quoted` paths (and in `JSONExtract` and typed `JSON`) is a Unix timestamp in seconds, consistent with the `Values` format, `CAST` and `toDateTime64`. Set this to `true` (or `SET compatibility = '26.7'`) to restore the pre-26.8 behavior, where a bare unquoted integer fed to a `DateTime64` column was read as the raw scaled value (ticks). The tab-separated, CSV and other escaped/whole-text formats are not governed by this setting."}, @@ -224,16 +211,6 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() {"query_plan_optimize_lazy_materialization_for_object_storage", false, true, "New setting to use lazy materialization for `ORDER BY ... LIMIT n` queries reading Parquet files from object storage (including Iceberg tables)."}, {"iceberg_compaction_max_rows_in_data_file", std::numeric_limits::max(), std::numeric_limits::max(), "New setting for the max rows of an iceberg data file produced by compaction, separate from the insert-time limit."}, {"iceberg_compaction_max_bytes_in_data_file", std::numeric_limits::max(), std::numeric_limits::max(), "New setting for the max bytes of an iceberg data file produced by compaction, separate from the insert-time limit."}, - {"input_format_arrow_use_native_reader", true, true, "Obsolete setting, the native ClickHouse reader is now always used for the `Arrow` and `ArrowStream` formats (the Apache Arrow library-based reader has been removed)."}, - {"output_format_arrow_use_native_writer", true, true, "Obsolete setting, the native ClickHouse writer is now always used for the `Arrow` and `ArrowStream` formats (the Apache Arrow library-based writer has been removed)."}, - {"distributed_cache_min_inflight_bytes_to_discard_connection_on_seek", 0, 4 * 1024 * 1024, "New setting to drop and reopen a distributed cache connection on a seek when too many in-flight bytes would otherwise be discarded. Defaults to 4 MiB; 0 restores the previous behavior (always reuse the connection via the read range id)."}, - {"input_format_parquet_spatial_filter_push_down", false, true, "New setting: skip GeoParquet row groups and pages based on spatial predicates and bounding box statistics"}, - {"use_text_index_negative_tokens_cache", false, true, "New setting to cache absent text index tokens and avoid repeated dictionary lookups."}, - {"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 (reader v3)."}, - }); - addSettingsChanges(settings_changes_history, "26.7", - { - {"analyzer_compatibility_allow_non_aggregate_in_having", false, false, "New compatibility setting. When enabled, the analyzer mimics the legacy `HAVING`-to-`WHERE` rewrite for non-aggregate AND-conjuncts instead of raising `NOT_AN_AGGREGATE`."}, {"dictionary_lazy_load", "auto", "auto", "New setting overriding the server setting `dictionaries_lazy_load` for an individual dictionary."}, {"discard_query_data", false, false, "New setting to skip sending query result rows to the client over the native TCP protocol."}, {"optimize_trivial_count_with_sparsity_filter", false, false, "New (experimental) setting to serve `SELECT count() FROM t WHERE ` from per-column `num_defaults` / `num_rows` recorded in `serialization.json` when `` partitions rows into defaults vs non-defaults."}, @@ -299,16 +276,10 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() {"object_storage_cluster_fallback_to_local_if_empty", false, false, "New setting"}, {"use_puffin_files_cache", false, true, "Enables cache of parsed Puffin file content such as deletion vectors."}, }); - }); - addSettingsChanges(settings_changes_history, "26.6", { {"analyzer_compatibility_apply_final_to_all_joined_tables", true, false, "Fixed a bug in the analyzer where FINAL on the left-most table of a JOIN was incorrectly applied to the other joined tables as well. previous_value=true so `compatibility` with versions before 26.6 restores the old behavior."}, {"cloud_mode_database_engine", 1, 1, "Obsolete setting, the database engine in Cloud no longer depends on it."}, - {"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 (reader v3)."}, - {"input_format_parquet_prefetch_bandwidth_hide_seconds", 0, 0, "New setting: read back-pressure for the Parquet v3 reader; stop prefetching compressed data pages once in-flight compressed bytes exceed this many seconds of measured read throughput. 0 (the default and the pre-existing behavior) disables the back-pressure."}, - {"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 skip data pages that are single-valued over a row subgroup. Disabled by default (costs a small extra read)."}, - {"input_format_parquet_fill_constant_pages", false, false, "New experimental setting: fill single-valued Parquet data pages from per-page Column Index statistics instead of decoding them, even when only part of a row subgroup is constant. Disabled by default."}, {"analyzer_compatibility_allow_non_aggregate_in_having", false, false, "New compatibility setting. When enabled, the new analyzer mimics the legacy `HAVING`-to-`WHERE` rewrite for non-aggregate AND-conjuncts instead of raising `NOT_AN_AGGREGATE`."}, {"reserve_memory", 0, 0, "New setting to reserve memory for specific workload before starting a query."}, {"input_format_parquet_prefetch_memory_fraction", 0.6, 0.6, "New setting to tune the Parquet reader split of the column-data memory budget between compressed read-ahead and decode."}, From 6281ea1caa77bc1c1c01465022e1435fdd9c7be0 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Mon, 30 Nov 2026 14:11:10 +0100 Subject: [PATCH 17/20] Parquet v3: give the constant-column tests free numbers Move the constant-column tests from 04811 and 04812 to the next free numbers, 05815 and 05816, as add-test would assign them. The comment in the constant-column test now says that the `c_dt` column needs a cast, so it is decoded normally and not materialized. Co-authored-by: Cursor --- ...uet_constant_column_optimization.reference | 12 +++ ...15_parquet_constant_column_optimization.sh | 69 ++++++++++++++++++ ...uet_all_null_column_optimization.reference | 14 ++++ ...16_parquet_all_null_column_optimization.sh | 73 +++++++++++++++++++ 4 files changed, 168 insertions(+) create mode 100644 tests/queries/0_stateless/05815_parquet_constant_column_optimization.reference create mode 100755 tests/queries/0_stateless/05815_parquet_constant_column_optimization.sh create mode 100644 tests/queries/0_stateless/05816_parquet_all_null_column_optimization.reference create mode 100755 tests/queries/0_stateless/05816_parquet_all_null_column_optimization.sh 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..472aad1059acd --- /dev/null +++ b/tests/queries/0_stateless/05815_parquet_constant_column_optimization.sh @@ -0,0 +1,69 @@ +#!/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 +" + +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 +" + +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}')" + +echo "-- filters on a constant column still work" +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_int = 42" +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_int = 43" + +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..21522716651db --- /dev/null +++ b/tests/queries/0_stateless/05816_parquet_all_null_column_optimization.sh @@ -0,0 +1,73 @@ +#!/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 +" + +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 +" + +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}')" + +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" +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_null IS NOT NULL" + +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 +" + +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}" From e7063148cf69178e84b8f96e9fd063c0d1ea403a Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Mon, 30 Nov 2026 14:11:33 +0100 Subject: [PATCH 18/20] Parquet v3: remove the old names of the constant-column tests The tests were renamed to 05815 and 05816 in the previous commit; the old files are removed here, since the rename was staged separately. Co-authored-by: Cursor --- ...uet_constant_column_optimization.reference | 12 --- ...11_parquet_constant_column_optimization.sh | 69 ------------------ ...uet_all_null_column_optimization.reference | 14 ---- ...12_parquet_all_null_column_optimization.sh | 73 ------------------- 4 files changed, 168 deletions(-) delete mode 100644 tests/queries/0_stateless/04811_parquet_constant_column_optimization.reference delete mode 100755 tests/queries/0_stateless/04811_parquet_constant_column_optimization.sh delete mode 100644 tests/queries/0_stateless/04812_parquet_all_null_column_optimization.reference delete mode 100755 tests/queries/0_stateless/04812_parquet_all_null_column_optimization.sh diff --git a/tests/queries/0_stateless/04811_parquet_constant_column_optimization.reference b/tests/queries/0_stateless/04811_parquet_constant_column_optimization.reference deleted file mode 100644 index 3328031ec73e1..0000000000000 --- a/tests/queries/0_stateless/04811_parquet_constant_column_optimization.reference +++ /dev/null @@ -1,12 +0,0 @@ --- 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/04811_parquet_constant_column_optimization.sh b/tests/queries/0_stateless/04811_parquet_constant_column_optimization.sh deleted file mode 100755 index 2a059de021871..0000000000000 --- a/tests/queries/0_stateless/04811_parquet_constant_column_optimization.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/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 with a DateTime hint, exercising the -# milliseconds -> seconds stats conversion (the value is in the post-cast output domain). -${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 -" - -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 -" - -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}')" - -echo "-- filters on a constant column still work" -${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_int = 42" -${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_int = 43" - -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/04812_parquet_all_null_column_optimization.reference b/tests/queries/0_stateless/04812_parquet_all_null_column_optimization.reference deleted file mode 100644 index dfda8ff8759cc..0000000000000 --- a/tests/queries/0_stateless/04812_parquet_all_null_column_optimization.reference +++ /dev/null @@ -1,14 +0,0 @@ --- 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/04812_parquet_all_null_column_optimization.sh b/tests/queries/0_stateless/04812_parquet_all_null_column_optimization.sh deleted file mode 100755 index 21522716651db..0000000000000 --- a/tests/queries/0_stateless/04812_parquet_all_null_column_optimization.sh +++ /dev/null @@ -1,73 +0,0 @@ -#!/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 -" - -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 -" - -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}')" - -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" -${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_null IS NOT NULL" - -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 -" - -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}" From d35eca067767e9251f08751e6b0cbd832619bac8 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Mon, 30 Nov 2026 14:11:35 +0100 Subject: [PATCH 19/20] Parquet v3: decode constant candidates without a cast only A constant column chunk is materialized from its decoded value, and the Column Index path (tier 2) relies on the same invariant: the value is the output value only when no post-decode cast is applied. Make the shared eligibility gate exclude columns that need a cast, so tier 1 and tier 2 agree. Decode the statistics value in the decoded type, since the three-argument `decodeField` overload no longer exists on this branch. A column that needs a cast, such as a `DateTime` written as `TIMESTAMP_MILLIS`, is now read and decoded normally. Co-authored-by: Cursor --- src/Processors/Formats/Impl/Parquet/Reader.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index 89dbe7e787a01..e532374aab6ec 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2617,6 +2617,11 @@ bool Reader::constColumnMaterializationEligible(const PrimitiveColumnInfo & colu 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; } @@ -2677,7 +2682,8 @@ void Reader::detectConstantColumn(ColumnChunk & column, const PrimitiveColumnInf /// a single value short enough to be stored exactly, so `is_*_value_exact` is implied. Field value; - column_info.decoder.decodeField(stats.min_value, /*is_max=*/ false, 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; From 816b6c2de361b508a93e5fab05e80d3abc80013b Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Mon, 30 Nov 2026 14:40:53 +0100 Subject: [PATCH 20/20] Parquet v3: skip constant-column optimization when checksums are verified A constant column chunk or subchunk is materialized from footer and Column Index statistics without reading its data pages, so page checksums (`input_format_parquet_verify_checksums`, default true) were silently not verified for those chunks. The regression showed up in `03408_parquet_checksums`, where a corrupted single-value column no longer reported the CRC error. Constant detection is now disabled when verification is requested, so such chunks are decoded normally. The optimization applies only when verification is turned off. Update `05815_parquet_constant_column_optimization` and `05816_parquet_all_null_column_optimization` to disable verification in their queries that exercise the optimization, and add `05817_parquet_constant_column_checksums` covering the default and the disabled cases. Document the interaction in `input_format_parquet_use_constant_column_optimization` and the design doc. Co-authored-by: Cursor --- .../parquet-v3-page-level-constant-column.md | 4 ++ src/Core/FormatFactorySettings.h | 2 +- .../Formats/Impl/Parquet/Reader.cpp | 4 ++ ...15_parquet_constant_column_optimization.sh | 9 +-- ...16_parquet_all_null_column_optimization.sh | 11 ++-- ...arquet_constant_column_checksums.reference | 7 +++ ...05817_parquet_constant_column_checksums.sh | 55 +++++++++++++++++++ 7 files changed, 82 insertions(+), 10 deletions(-) create mode 100644 tests/queries/0_stateless/05817_parquet_constant_column_checksums.reference create mode 100755 tests/queries/0_stateless/05817_parquet_constant_column_checksums.sh diff --git a/docs/design/parquet-v3-page-level-constant-column.md b/docs/design/parquet-v3-page-level-constant-column.md index 80bb8c2de78da..dc5224e7dd690 100644 --- a/docs/design/parquet-v3-page-level-constant-column.md +++ b/docs/design/parquet-v3-page-level-constant-column.md @@ -89,6 +89,10 @@ touch the `allow_stats` decision itself. - 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. diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index fd6afd6a78991..c727ed8cd3d1b 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -237,7 +237,7 @@ When reading GeoParquet files, skip whole row groups and, together with `input_f 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. +When a Parquet column chunk provably holds a single value in every row (according to its min/max statistics), materialize that value directly instead of reading and decoding the column's data pages. Not applied when `input_format_parquet_verify_checksums` is enabled, because the data pages of such chunks are not read and their checksums would not be verified. )", 0) \ DECLARE(Bool, input_format_parquet_use_column_index_for_constant_columns, false, R"( Load the Parquet Column Index for read columns that have no predicate of their own, so the constant-column optimization can also skip data pages that are single-valued over a row subgroup (not just over a whole column chunk). Costs a small extra read of the (tiny) Column Index; only worthwhile when columns are sorted or low-cardinality. Applies only when `input_format_parquet_use_constant_column_optimization` is enabled. diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp index e532374aab6ec..fdf5dcc142717 100644 --- a/src/Processors/Formats/Impl/Parquet/Reader.cpp +++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp @@ -2599,6 +2599,10 @@ bool Reader::constColumnMaterializationEligible(const PrimitiveColumnInfo & colu { 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; diff --git a/tests/queries/0_stateless/05815_parquet_constant_column_optimization.sh b/tests/queries/0_stateless/05815_parquet_constant_column_optimization.sh index 472aad1059acd..dc8820a69fbdf 100755 --- a/tests/queries/0_stateless/05815_parquet_constant_column_optimization.sh +++ b/tests/queries/0_stateless/05815_parquet_constant_column_optimization.sh @@ -36,6 +36,7 @@ ${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)" @@ -43,15 +44,15 @@ ${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 + 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}')" +${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" -${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_int = 43" +${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 " 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 index 21522716651db..1e29416cde529 100755 --- a/tests/queries/0_stateless/05816_parquet_all_null_column_optimization.sh +++ b/tests/queries/0_stateless/05816_parquet_all_null_column_optimization.sh @@ -32,6 +32,7 @@ ${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)" @@ -39,22 +40,22 @@ ${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 + 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}')" +${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" -${CLICKHOUSE_CLIENT} -q "SELECT count() FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') WHERE c_null IS NOT NULL" +${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 + SETTINGS input_format_null_as_default = 1, input_format_parquet_verify_checksums = 0 " echo "-- optimization fired only when enabled" 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}"