Skip to content

Optimize filtered constant columns - #105541

Merged
alexey-milovidov merged 107 commits into
ClickHouse:masterfrom
niyue:perf/const-column-filter
Nov 1, 2026
Merged

alexey-milovidov merged 107 commits into
ClickHouse:masterfrom
niyue:perf/const-column-filter

Conversation

@niyue

@niyue niyue commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Optimizes FilterTransform to replace physical input columns with ColumnConst after filters that prove the column has a single value, such as WHERE x = 'hello'. This reduces work for later pipeline steps and lets downstream expressions observe the filtered column as constant.

The optimization currently handles equality predicates through AND conditions and preserves conservative behavior for OR, NOT, and multi-value predicates.

This PR partially fixes issue: #34326. It covers the ColumnConst optimization for columns constrained by equality filters, while the remaining LowCardinality part is left out because changing a filtered column to LowCardinality may alter the column type/representation contract which seems more risky.

Changelog category (leave one):

  • Performance Improvement

Changelog entry:

  • Optimize filtering by replacing columns constrained to a single value by WHERE equality conditions with ColumnConst.

Performance benchmark

I measured this locally with a RelWithDebInfo build. Each case uses clickhouse benchmark --iterations 10; the table reports the median (50%) latency.

Case Query Before fix median After fix median Improvement
group_by_const_keys_after_filter SELECT count(), sum(v) FROM constant_column_after_filter WHERE k1 = 42 AND k2 = 43 AND k3 = 44 AND k4 = 45 AND k5 = 46 AND k6 = 47 AND k7 = 48 AND k8 = 49 GROUP BY k1, k2, k3, k4, k5, k6, k7, k8 FORMAT Null SETTINGS max_threads = 1, optimize_move_to_prewhere = 0, query_plan_optimize_prewhere = 0, query_plan_optimize_lazy_materialization = 0 0.941 sec 0.792 sec 15.8% faster
expressions_on_const_columns_after_filter SELECT sum(length(toString(k1))), sum(length(toString(k2))), sum(length(toString(k3))), sum(length(toString(k4))), sum(length(toString(k5))), sum(length(toString(k6))), sum(length(toString(k7))), sum(length(toString(k8))) FROM constant_column_after_filter WHERE k1 = 42 AND k2 = 43 AND k3 = 44 AND k4 = 45 AND k5 = 46 AND k6 = 47 AND k7 = 48 AND k8 = 49 FORMAT Null SETTINGS max_threads = 1, optimize_move_to_prewhere = 0, query_plan_optimize_prewhere = 0, query_plan_optimize_lazy_materialization = 0 0.768 sec 0.434 sec 43.5% faster

Note

Medium Risk
Touches core query execution filtering and mutates output column representations, which could subtly affect type/nullable/LC behavior; additional guards reduce risk but correctness/perf impacts span many queries.

Overview
Filter optimization: FilterTransform now analyzes the filter ActionsDAG and, for and-combined equals predicates against constants (e.g. x = 'hello'), records columns that become single-valued and rewrites those output columns to ColumnConst after filtering.

The rewrite is applied on fast paths (all-rows-pass / constant-true filter) and after partial filtering, with safeguards to skip float-related cases and to avoid unsafe conversions (notably float/decimal comparisons), plus handling for nullable/low-cardinality-nullable columns.

Adds a new stateless test (04259_filter_constant_column_after_where) covering aliases, multiple AND equalities, non-handled OR/NOT, nullable/low-cardinality cases, and float/decimal edge conditions.

Reviewed by Cursor Bugbot for commit 9a6d76a. Bugbot is set up for automated code reviews on this repo. Configure here.


Workflow [PR]
Sync PR [sync-upstream/pr/105541]

Version info

  • Merged into: 26.11.1.1030-master (included in 26.11 and later)

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [06869da]

Summary: ✅


AI Review

Summary

The PR replaces eligible input columns with ColumnConst after equality filters and updates downstream processing to handle those columns. No outstanding findings remain. The previously reported loss of optimize_constant_columns_after_filter in deferred ReadFromMergeTree filters is fixed in the current head.

Missing context / blind spots
  • ⚠️ Current-head CI is still running. Focused local probes passed using the preceding ARM release binary at 560c719eed39c2d398460fee412c36b5cc37fe02; the latest setting propagation change was verified in source and has regression coverage. Completion of current-head functional CI would close the remaining execution gap.
Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 21, 2026
@niyue
niyue force-pushed the perf/const-column-filter branch from f18c917 to ae0a620 Compare May 22, 2026 13:31
niyue added a commit to niyue/ClickHouse that referenced this pull request May 22, 2026
Avoid replacing floating-point columns after `equals`, because `+0.0` and `-0.0` compare equal but have different bit representations. Materialize `Nullable` constant columns before passing them downstream to avoid invalid keys in grouping sets with `group_by_use_nulls`.

PR: ClickHouse#105541

Tests: ninja -C build programs/clickhouse

Tests: tests/clickhouse-test --no-random-settings --no-random-merge-tree-settings 04259_filter_constant_column_after_where

Tests: local `03305_mergine_aggregated_filter_push_down` smoke with `127.0.0.{1,1}` because this macOS host has no `127.0.0.2` loopback alias
niyue added 4 commits May 22, 2026 22:34
Cover additional `FilterTransform` cases for filtered `ColumnConst` columns, including convertible constants, non-input expressions, `Nullable`, `LowCardinality`, omitted filtered columns, partially omitted equality columns, and empty results.
Avoid replacing floating-point columns after `equals`, because `+0.0` and `-0.0` compare equal but have different bit representations. Materialize `Nullable` constant columns before passing them downstream to avoid invalid keys in grouping sets with `group_by_use_nulls`.

PR: ClickHouse#105541

Tests: ninja -C build programs/clickhouse

Tests: tests/clickhouse-test --no-random-settings --no-random-merge-tree-settings 04259_filter_constant_column_after_where

Tests: local `03305_mergine_aggregated_filter_push_down` smoke with `127.0.0.{1,1}` because this macOS host has no `127.0.0.2` loopback alias
Skip the constant-column rewrite when an `equals` predicate constrains a `Decimal` column with a floating-point constant. Such comparisons can keep multiple distinct `Decimal` values after conversion through floating-point comparison paths, so replacing the result with one converted constant changes query-visible output.
@niyue
niyue force-pushed the perf/const-column-filter branch from ae0a620 to 34f9cd9 Compare May 22, 2026 15:45
niyue added 2 commits May 23, 2026 15:31
Make the `equals` safety check recursive over constrained and constant types before replacing filtered columns with `ColumnConst`. This skips rewrites when the constrained type contains `Float`, or when it contains `Decimal` and the constant side contains `Float`.

Add stateless coverage for nested `Tuple(Float64)` and nested `Tuple(Decimal128)` predicates that must preserve distinct surviving values.

Review: ClickHouse#105541 (comment)
niyue added 2 commits May 24, 2026 14:14
Skip the constant-column rewrite when the constrained column type contains `Dynamic`, because runtime variants are not visible through static child-type traversal and can carry non-representation-unique values.
`equals` between `String` and `FixedString` can keep multiple distinct `String` payloads because of zero-padded `FixedString` comparison semantics. Do not replace the filtered `String` column with a single `ColumnConst` in that case
Comment thread src/Interpreters/Aggregator.cpp Resolved
`MergingAggregated` can receive partially aggregated blocks after expression or filter steps. Numeric aggregation merge methods read key columns through raw data, so a  key can be read past its single nested value and produce wrong grouping keys.

Materialize only key columns before merge and keep aggregate state columns unchanged.
@niyue
niyue force-pushed the perf/const-column-filter branch from d6403a1 to 73f7811 Compare May 24, 2026 15:59
niyue added 4 commits May 25, 2026 11:57
Fix `04259_filter_constant_column_after_where` by fixing `query_plan_merge_filters` and `query_plan_optimize_lazy_materialization` after the explicit filter-merge coverage queries.

The test checks `dumpColumnStructure`, so randomized filter splitting and lazy materialization can change whether a column is observed as `ColumnConst` or a full column without changing query semantics.
The `equals` function for `Variant` can keep rows with different active variants for the same literal value, such as `Int8(1)` and `UInt8(1)` in `Variant(Int8, UInt8)`. Rewriting the constrained column to one `ColumnConst` would collapse those rows to a single active variant.

Skip the optimization when the constrained result type recursively contains `Variant`, and cover both direct `Variant` and nested `Tuple(Variant)` cases.

Review: ClickHouse#105541 (comment)

Tests: `ninja -C build src/CMakeFiles/dbms.dir/Processors/Transforms/FilterTransform.cpp.o > build/build_filter_transform_variant_guard_object_20260525.log 2>&1`
Comment thread src/Interpreters/Aggregator.cpp Resolved
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 1, 2026
Merged via the queue into ClickHouse:master with commit e5e601d Nov 1, 2026
179 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 1, 2026
@watson-ch

watson-ch Bot commented Nov 2, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2163

Labels added:

  • v26.4-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 2, 2026
@alexey-milovidov alexey-milovidov removed v26.4-must-backport pr-synced-to-cloud The PR is synced to the cloud repo pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Nov 2, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 2, 2026
@watson-ch

watson-ch Bot commented Nov 2, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2163

Labels added:

  • v26.4-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 2, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 2, 2026
@watson-ch watson-ch Bot added v26.4-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Nov 4, 2026
@watson-ch

watson-ch Bot commented Nov 4, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2163

Labels added:

  • v26.4-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 4, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 4, 2026
PedroTadim pushed a commit to hsusul/ClickHouse that referenced this pull request Nov 4, 2026
Add a triggered expansion to `.claude/skills/review/SKILL.md` for changes
that let a component produce its output in a form it did not produce
before. It asks the review to enumerate the consumers (including internal
reuses of the component) and list how each handles the new form, to check
that a claimed normalization point precedes every use on each path, to
ask for one fix where a recurring class starts instead of another point
fix, and to require tests whose inputs reach the form-specific code of a
consumer.

The AI review of ClickHouse#105541 accepted the conversion in
`MergeTreeDataPartWriterOnDisk::prepareBlockForWriting` as the boundary
for constant columns, while `MergeTreeDataWriter::writeProjectionPartImpl`
used the block before any writer existed (`infos.add`, sorting,
`mergeBlock`). The test it asked for used only `String` and `DateTime`
columns, which reach the generic `SerializationInfo::add`, not the
downcast in `SerializationInfoTuple::add`. Consumers were reported one per
round for five months.

Asked for in ClickHouse#128533 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.