Repository navigation
Constant filter folding under materialize - #105987
Conversation
|
Workflow [PR], commit [72bdf65] Summary: ✅
AI ReviewSummaryThis PR restores constant-filter folding through Missing context / blind spots
Findings❌ Blockers
Final VerdictNot ready. The remaining tuple-carrier hole is still user-visible on storage-side filters, and the LLVM Coverage ReportMeasured on commit 72bdf65.
Changed lines: Changed C/C++ lines covered: 125/132 (94.70%) · Uncovered code |
…hrough-materialize-conflicts
…hrough-materialize-conflicts # Conflicts: # src/Interpreters/ActionsDAG.cpp # src/Interpreters/ActionsDAG.h
…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]>
|
Fixing PR: #120526.
The fix is Validated against a forced reproduction rather than the vanished flake: with a stale |
…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
…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
|
On adapted TPC-DS SF10 this fold is a clear win on one shipped query and a reproducible regression on another.
Both are ClickHouse's own The fold engages as intended: query_04's plan goes from 54 For query_11 the dead-branch cost is removed as expected, but the surviving work gets slower. One profiled execution per arm,
Setup: 4 vCPU / 30 GiB Xeon 8375C, one server at a time on the same data directory, suite settings ( |
| return; | ||
|
|
||
| FoldCache fold_cache; | ||
| auto folded = tryFoldPredicate(filter_node, fold_cache); |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
|
Actually, the description is ok. |
|
@yariks5s @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
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]>
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]>
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]>
Under the analyzer, a filter that is constant once the
materializewrappers inside it arestripped is no longer evaluated per row: comparison, logical and null predicates over
materialized constants are folded to a constant, which lets filter pushdown and
PREWHEREpruning skip the reads again, as the old analyzer did.
Closes: #78166
Changelog category (leave one):
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 overmaterialized constants are now folded and pushed down, reducing unnecessary reads in
WHERE,PREWHEREandUNIONbranches.Workflow [PR]
Sync PR [sync-upstream/pr/105987]
Version info
26.10.1.485-master(included in26.10and later)