Skip to content

Constant filter folding under materialize - #105987

Merged
alexey-milovidov merged 71 commits into
masterfrom
yarik/fold-filter-through-materialize
Sep 23, 2026
Merged

alexey-milovidov merged 71 commits into
masterfrom
yarik/fold-filter-through-materialize

Conversation

@yariks5s

@yariks5s yariks5s commented May 27, 2026 •

Copy link
Copy Markdown
Member

Under the analyzer, a filter that is constant once the materialize wrappers inside it are
stripped is no longer evaluated per row: comparison, logical and null predicates over
materialized constants are folded to a constant, which lets filter pushdown and PREWHERE
pruning skip the reads again, as the old analyzer did.

Closes: #78166

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Under the analyzer, constant comparison, logical and null (IS NULL / IS NOT NULL) filters over
materialized constants are now folded and pushed down, reducing unnecessary reads in WHERE,
PREWHERE and UNION branches.


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

Version info

  • Merged into: 26.10.1.485-master (included in 26.10 and later)

@clickhouse-gh

clickhouse-gh Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [72bdf65]

Summary: ✅


AI Review

Summary

This PR restores constant-filter folding through materialize for dropped filter outputs under the analyzer, including PREWHERE and pushed-down filters. The direction is good and many earlier semantic holes were addressed, but I do not think it is ready to merge: one tuple-carrier correctness hole is still open on storage-side filters, and there is now an unresolved double-digit regression on a shipped TPC-DS query.

Missing context / blind spots
  • ⚠️ I could not run the new stateless cases locally because this checkout only contains the synthetic merge commit and no build artifacts. The tuple finding below is from code-path tracing, and the performance finding relies on the benchmark report already posted on the PR.
Findings

❌ Blockers

  • [src/Processors/QueryPlan/FilterStep.cpp:132], [src/Interpreters/ActionsDAG.cpp:1119-1145], [src/Functions/FunctionsComparison.h:1281-1306] Storage-side folding still changes a mixed tuple comparison from an exception into a match. pruneFilterDAGOutputsByPosition now folds PREWHERE / row-policy filters before any header evaluation runs, so PREWHERE materialize(tuple('1')) = tuple(toUInt8(1)) reaches tryFoldPredicate with a stripped materialize and then executeTuple compares Const(String) against Const(UInt8), taking the const-string path and folding to 1. The unfurled runtime path still raises NO_COMMON_TYPE, so this can silently turn an exception into returned rows on ReadFromMergeTree. Suggested fix: restore a recursive tuple string-vs-non-string guard for through_materialize carriers, or defer the storage-side fold until after the same validation path that ordinary FilterStep construction goes through.
  • [src/Interpreters/ActionsDAG.cpp:1422-1430] The rewrite is still unconditional even though the benchmark report on this PR shows a reproducible +23.4% regression on TPC-DS query_11 (8/8 non-overlapping reps, unchanged read_rows, and slower AggregatingTransform / JoiningTransform). That is one of ClickHouse's own shipped benchmark queries under tests/benchmarks/tpc-ds/queries, so landing this before we understand or gate the bad shape would trade one optimizer hole for a material regression. Suggested fix: reproduce query_11, identify which surviving-plan change causes the slowdown, and add a heuristic / guard if the regression is real.
Final Verdict

Not ready. The remaining tuple-carrier hole is still user-visible on storage-side filters, and the query_11 regression needs to be explained or gated before this optimizer rewrite is safe to merge.

LLVM Coverage Report

Measured on commit 72bdf65.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 125/132 (94.70%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 27, 2026
@KochetovNicolai KochetovNicolai self-assigned this May 27, 2026
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Comment thread src/Processors/QueryPlan/FilterStep.cpp Resolved
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
yariks5s added 2 commits June 18, 2026 16:13
…hrough-materialize-conflicts

# Conflicts:
#	src/Interpreters/ActionsDAG.cpp
#	src/Interpreters/ActionsDAG.h
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
…lizeOutwardForConstants

DAG-stored ColumnConsts are size 0 by convention; some functions
(e.g. moduloOrNull) misbehave on size-0 input. Match getFunctionArguments
and resize to size 1 before calling node.function->execute, so we don't
turn a valid filter into a planning-time exception.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator

Fixing PR: #120526.

libmariadb/secure/openssl.c reads SSL_get_error() without ever clearing the calling thread's OpenSSL error queue, which is that function's documented precondition. ossl_ssl_get_error() inspects ERR_peek_error() first and returns SSL_ERROR_SYSCALL for any ERR_LIB_SYS entry before it looks at SSL_want_read() and the BIO retry flag, so a leftover entry turns a read OpenSSL had already marked retryable into a fatal one. ma_tls_set_error() then pops that stale entry, gets NULL from ERR_reason_error_string() (NULL for every system error by design) and falls back to strerror_r(errno), which is where Interrupted system call (4) comes from. mysqlxx always uses TLS and the sampling profiler is on by default, so these reads take periodic signals; the TLS path cannot use ma_recv()'s EINTR loop, because OPENSSL_USE_BIOMETHOD is undefined there and SSL_set_fd() lets OpenSSL read the socket directly.

The fix is ERR_clear_error() before every SSL call whose result is read through SSL_get_error(). #120526 is the contrib/mariadb-connector-c pin bump; the code change itself is ClickHouse/mariadb-connector-c#25 and needs to merge first.

Validated against a forced reproduction rather than the vanished flake: with a stale ERR_LIB_SYS entry forced on the reading thread, 20 of 20 MySQL reads fail with that exact message and 02479_mysql_connect_to_self fails 2 to 3 of 20 runs; with the fix that same workload is 20 of 20 green and 02479 is 50 of 50, while 125319 stale entries were still observed at SSL call entry, so the green arm is not vacuous. Un-injected, 428000 instrumented reads showed none, which is why it is rare rather than absent.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 17, 2026
…nt reads

Bump contrib/mariadb-connector-c to pick up a single connector change:
ERR_clear_error() before every SSL_connect/SSL_read/SSL_write whose result is
interpreted through SSL_get_error(), plus capturing errno as the first
statement of ma_tls_set_error().

SSL_get_error() only reports the retry flags of the operation just attempted
while the calling thread's OpenSSL error queue is empty, and openssl.c never
cleared it. A leftover ERR_LIB_SYS entry from any earlier OpenSSL operation on
the same thread is therefore reported first (ossl_ssl_get_error() returns
SSL_ERROR_SYSCALL for ERR_LIB_SYS before it looks at SSL_want_read() and the
BIO retry flag), so a read that OpenSSL had already marked retryable becomes
fatal. ma_tls_set_error() then pops the stale entry, gets NULL from
ERR_reason_error_string() and prints strerror_r(errno) instead, producing

  mysqlxx::BadQuery: TLS/SSL error: Interrupted system call (4)

on a healthy connection, with an errno that need not belong to the failing
call. Every mysql() table function, MySQL table/database engine and MySQL
dictionary read is affected: mysqlxx::Connection::connect enables TLS
unconditionally via mysql_ssl_set, the sampling query profiler is on by
default so query threads take periodic signals, and the TLS path bypasses
ma_recv()'s EINTR retry loop because OPENSSL_USE_BIOMETHOD is undefined and
SSL_set_fd() lets OpenSSL read the socket directly.

No regression test ships with this. With an empty error queue the message is
unreachable on the old pin: sock_read() zeroes errno before every recv, EINTR is
classified retryable, and pvio_socket_wait_io_or_timeout() re-polls it against
its deadline and reports ETIMEDOUT. 428000 instrumented un-injected reads
produced none, and no SQL-reachable producer of a stale ERR_LIB_SYS entry was
found, so the failing arm of a functional test would be unobservable. The fix
was validated by forcing a stale entry on the reading thread instead: 20 of 20
reads and 2-3 of 20 02479_mysql_connect_to_self runs failed before it, 20 of 20
and 50 of 50 passed after, and 125319 stale entries were still measured at SSL
entry on the green arm, so that arm is not vacuous.

The changelog category is the one the fix-carrying contrib bumps use (usearch
ClickHouse#118828, openssl ClickHouse#118927) rather than Bug Fix: the change in this repository is
only the dependency pin, and the Bug Fix category's validation expects a
regression test that reddens on master, which this defect cannot supply.

Related: ClickHouse#105987
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 17, 2026
…nt reads

Bump contrib/mariadb-connector-c to pick up a single connector change:
ERR_clear_error() before every SSL_connect/SSL_read/SSL_write whose result is
interpreted through SSL_get_error(), plus capturing errno as the first
statement of ma_tls_set_error().

SSL_get_error() only reports the retry flags of the operation just attempted
while the calling thread's OpenSSL error queue is empty, and openssl.c never
cleared it. A leftover ERR_LIB_SYS entry from any earlier OpenSSL operation on
the same thread is therefore reported first (ossl_ssl_get_error() returns
SSL_ERROR_SYSCALL for ERR_LIB_SYS before it looks at SSL_want_read() and the
BIO retry flag), so a read that OpenSSL had already marked retryable becomes
fatal. ma_tls_set_error() then pops the stale entry, gets NULL from
ERR_reason_error_string() and prints strerror_r(errno) instead, producing

  mysqlxx::BadQuery: TLS/SSL error: Interrupted system call (4)

on a healthy connection, with an errno that need not belong to the failing
call. Every mysql() table function, MySQL table/database engine and MySQL
dictionary read is affected: mysqlxx::Connection::connect enables TLS
unconditionally via mysql_ssl_set, the sampling query profiler is on by
default so query threads take periodic signals, and the TLS path bypasses
ma_recv()'s EINTR retry loop because OPENSSL_USE_BIOMETHOD is undefined and
SSL_set_fd() lets OpenSSL read the socket directly.

No regression test ships with this. With an empty error queue the message is
unreachable on the old pin: sock_read() zeroes errno before every recv, EINTR is
classified retryable, and pvio_socket_wait_io_or_timeout() re-polls it against
its deadline and reports ETIMEDOUT. 428000 instrumented un-injected reads
produced none, and no SQL-reachable producer of a stale ERR_LIB_SYS entry was
found, so the failing arm of a functional test would be unobservable. The fix
was validated by forcing a stale entry on the reading thread instead: 20 of 20
reads and 2-3 of 20 02479_mysql_connect_to_self runs failed before it, 20 of 20
and 50 of 50 passed after, and 125319 stale entries were still measured at SSL
entry on the green arm, so that arm is not vacuous.

The changelog category is the one the fix-carrying contrib bumps use (usearch
ClickHouse#118828, openssl ClickHouse#118927) rather than Bug Fix: the change in this repository is
only the dependency pin, and the Bug Fix category's validation expects a
regression test that reddens on master, which this defect cannot supply.

Connector change: ClickHouse/mariadb-connector-c#25
Related: ClickHouse#105987
@snelheidai

Copy link
Copy Markdown

On adapted TPC-DS SF10 this fold is a clear win on one shipped query and a reproducible regression on another.

query base with this PR latency peak memory
query_04 2621 ms 2359 ms -10.0% 1419 -> 306 MiB (-78%)
query_11 2576 ms 3178 ms +23.4% 890 -> 552 MiB (-38%)

Both are ClickHouse's own tests/benchmarks/tpc-ds/queries. Each builds a CTE as a UNION ALL of branches tagged with a constant discriminator ('s' AS sale_type / 'c' / 'w'; query_11 has only 's' and 'w') and references it several times, filtering each reference on that discriminator. So query_04 has 18 branch instances of which 12 are dead, and query_11 has 8 of which 4 are dead.

The fold engages as intended: query_04's plan goes from 54 Filter column: materialize(...) steps to 18, with 36 becoming Filter column: 0; query_11 goes 24 -> 8 with 12 folded. Answers are byte-identical per query across arms and read_rows is unchanged (104,237,930 and 74,289,310).

For query_11 the dead-branch cost is removed as expected, but the surviving work gets slower. One profiled execution per arm, elapsed_us summed over processor instances, instance count in brackets:

transform base with this PR
FillingRightJoinSide 1458 ms [37] 139 ms [34]
AggregatingTransform 1703 ms [20] 4243 ms [20]
JoiningTransform 2942 ms [56] 4255 ms [56]
FilterTransform 167 ms [64] 64 ms [68]
MergeTreeSelect 3252 ms 3026 ms

AggregatingTransform keeps the same instance count and produces the same 548,691 rows from the same 14,888,402 scanned rows, so it is the same aggregation taking 2.5x longer, and peak memory falls at the same time, which rules out memory pressure. BuildRuntimeFilterTransform sees 14,387,671 build rows in base against 1,581,835 with the PR, so the plan around the surviving branches changes too, not only the dead ones. That surviving-branch slowdown is the part I would want understood before this lands.

Setup: 4 vCPU / 30 GiB Xeon 8375C, one server at a time on the same data directory, suite settings (join_use_nulls=1, group_by_use_nulls=1, union/intersect DISTINCT, joined_subquery_requires_alias=0), server restarted and re-warmed per arm, 4 alternating reps per run and 8 per arm across two runs. Per-rep ranges do not overlap between arms (query_11 base 2554-2596 vs 3148-3237 ms; query_04 2585-2653 vs 2324-2452 ms). This is an adapted TPC-DS at SF10, not an audited TPC result. The two binaries differ only by this PR's cumulative diff at 0635d303a85f, applied onto 1e93c0a25f1 (master of 2026-09-15) rather than the PR's own merge base; that base carries one local optimizer patch of ours, so the table above is the run with it disabled in both arms, and the earlier run with it enabled in both arms agreed (query_04 -9.2%, query_11 +23.1%).

return;

FoldCache fold_cache;
auto folded = tryFoldPredicate(filter_node, fold_cache);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fold is still unconditional here, but the benchmark report already posted on this PR shows a reproducible regression on a shipped query: adapted TPC-DS query_11 goes from 2576 ms to 3178 ms (+23.4%) across 8/8 non-overlapping reps, with unchanged read_rows and slower AggregatingTransform / JoiningTransform on the surviving branches. That means this rewrite is changing more than dead-branch elimination; it is perturbing the remaining plan enough to lose performance on tests/benchmarks/tpc-ds/queries/query_11.sql.

Before this lands we need either a root-cause analysis showing why that benchmark is misleading, or a guard / heuristic that skips the bad shape. Merging an unconditional optimizer rewrite with an unresolved double-digit regression on one of our own shipped benchmark queries looks too risky.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly ok. The implementation is somewhat ad-hoc. And the PR description does not tell about the actual use-case: UNION ALL with constants in SELECT queries. It tells about materialize but it isn't the point.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 23, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Actually, the description is ok.

Merged via the queue into master with commit 10aad04 Sep 23, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the yarik/fold-filter-through-materialize branch September 23, 2026 02:50
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@yariks5s @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 26, 2026
The probe matched the pushed predicate by name. Since ClickHouse#105987 a FilterStep
that drops its filter column folds a predicate over materialized constants,
so the two filters this rewrite clones into the INTERSECT ALL branches now
render as `Filter column: NULL` instead of
`materialize(NULL) = materialize(NULL)`, and the probe read 0 instead of 2.
The master UNION ALL pushdown renders its branch filters the same way.

The rewrite itself is unchanged: no filter above IntersectOrExcept and one in
each branch. Count `Filter column:` lines instead, which keeps the pinned
property (2 with the pushdown, 1 without) independent of the predicate's
spelling. On a master build without this PR the probe reads 1 with the
pushdown enabled, so it still fails when the rewrite is absent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
AdeilH pushed a commit to AdeilH/ClickHouse that referenced this pull request Nov 6, 2026
A filter on a constant column of UNION ALL branches (`'s' AS sale_type` in
TPC-DS q4, q11, q74) reaches each branch as `materialize('s') = 's'`, next to
the branch's own conditions. `materialize` stops constant folding, and
`foldFilterPredicateThroughMaterialize` (ClickHouse#105987) folds only a filter that is
constant as a whole, so the conjunct stays. `ConditionSelectivityEstimator`
then priced it as a condition on an expression that is not a table column:
1% for `=` and 33% for `<`/`>`. In q74 `date_dim` was estimated at 3 rows
instead of 358, and join reordering built the hash table on the
`store_sales JOIN date_dim` side (14M rows at SF10) instead of `customer`.

`extractAtomFromTree` now decides `equals`, `notEquals`, `less`, `greater`,
`lessOrEquals`, `greaterOrEquals` of two constants with at least one behind
`materialize`, and `isNull`/`isNotNull` of such a constant, as ALWAYS_TRUE or
ALWAYS_FALSE. A constant-folded node under `materialize` counts too, since
`makeConvertingActions` puts the `_CAST` of a branch constant before
`materialize`.

Comparisons are decided with `accurateEquals`/`accurateLess`/
`accurateLessOrEqual`, only when both values have one totally ordered scalar
type after removing `LowCardinality`/`Nullable` (the type list of
`isAlwaysTrueEquality`, now shared) or are both integers. For these pairs the
`Field` comparison agrees with the comparison functions (Enum by value,
Decimal at the same scale, signed against unsigned through `accurate::lessOp`)
and cannot throw, so no try/catch is needed. Float, cross-type pairs (String
against Enum, see ClickHouse#121723), composite types and `IN` keep their default
estimate. A comparison with a NULL constant is not decided: it is NULL, not
FALSE, and ALWAYS_FALSE would turn into ALWAYS_TRUE under `NOT`.

As in ClickHouse#126131, only the estimate changes: the executed filter, results and
exceptions are the same. Removing the conjunct from the plan instead would
also move runtime filters and PREWHERE grouping (the first version of
ClickHouse#126131 slowed TPC-H Q4 over Iceberg that way, ClickHouse#122452), and would widen the
reach of ClickHouse#121723.

Analysis and original patch by snelheidai in ClickHouse#128482.

Closes ClickHouse#128482

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ylw510 pushed a commit to ylw510/ClickHouse that referenced this pull request Nov 11, 2026
Since ClickHouse#105987 a pushed-down predicate such as `materialize('x') = 'y'` folds a
UNION ALL branch filter like `and(in(c1, __set), materialize('x') = 'y')` to the
constant 0. The branch can no longer produce a row and nothing in it uses its IN
set, but the branch's `DelayedCreatingSetsStep` still holds the set, so
`addStepsToBuildSets` builds it. Before ClickHouse#105987 such sets were also built, but in
place and one after another during planning (MergeTree part pruning of the
unfolded filter); after the fold they are built by `CreatingSetsTransform` at
execution, concurrently with each other and with the main query. On the query
from ClickHouse#130319 (three `IN (SELECT ... FROM cte)` branches, two of them dead) this
raised peak memory from 1.36 GB to 4.03 GB.

When the steps below a `DelayedCreatingSetsStep` are only expressions and
filters and one of them is a filter whose column is a constant that the runtime
treats as always false (`ConstantFilterDescription`, as in `FilterTransform`),
no row reaches any step that can use the scope's sets. Replace that filter's
input with `ReadNothingStep`, so nothing below it runs (and nested scopes are
not expanded), and detach the sets. This runs in pre-order in
`addStepsToBuildSets`, on the final plan, so it covers every producer of a
plan-time constant-false filter. A totals stream passes `FilterTransform`
unfiltered, so an input that can produce totals is refused; `canProduceTotals`
is moved to `Optimizations/Utils` from `shortCircuitConstantFalseJoin.cpp` for
this.

Not covered: a GLOBAL IN subquery against `remote()` is executed while the shard
query tree is built, before plan optimization; a union between the set step and
the filter is refused.

Closes ClickHouse#130319

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

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

More reading rows in the analyzer

9 participants