Repository navigation
Conversation
…he AND
`tryOptimizeAndCompareNotEqualsChain` prunes always-true comparisons out of an
`AND` and, when a single operand survives, replaces the whole node with it. That
substitution reduced the survivor to a boolean on only one of its three paths. A
survivor whose declared type is type-equal to the `AND`'s was installed raw
(`DataTypeUInt8::equals` compares typeids, so `UInt8` and `Bool` both qualify),
and a `LowCardinality(UInt8)` survivor was merely cast, which preserves the value
instead of reducing it to 0 or 1. So
SELECT materialize(2::UInt8) AND (materialize(7::UInt8) < 300)
returned `2` where `AND` returns `1`, with no non-default setting. The block's own
comment already stated the invariant those two paths broke.
A survivor that is a recognized boolean function is now installed as-is and cast
to the `AND`'s type when it differs, which is the same gate
`tryOptimizeOutRedundantEquals` applies to the same decision. Any other survivor
keeps the `AND` and gains a constant `1` operand, so `and` performs the `!= 0`
itself: `tryReplaceOrEqualsChainWithIn` adds a stub `0` to an `or` for this
reason, and `tryOptimizeCommonExpressionsInAnd` already uses this `and(arg, 1)`
form. Typing the stub as the `AND`'s result type keeps a `Bool` expression
`Bool`, which a type comparison alone cannot do.
Keeping the `AND` also keeps index analysis intact. Wrapping the survivor in a
new function hides an index atom from the skip-index and key-condition builders,
which resolve a key column from the atom's own arguments, so
`hasToken(msg, 'needle') AND (severity < 300)` would stop consulting a
`tokenbf_v1` index that it uses today.
…lable
`registerNullableGroupByKeys` stores a GROUP BY key unwrapped and hands every
other resolution of the same expression a `Nullable`-converted clone of it, so
under `group_by_use_nulls` with `ROLLUP`, `CUBE` or `GROUPING SETS` the key and
its copies are the same tree with different types. Of this pass's four rewrite
sites, `tryReplaceOrEqualsChainWithIn` and `tryOptimizeOutRedundantEquals`
repair that wrapper and so move a key together with its copies, while both
`and`-chain sites decline on a `Nullable` result and can only move the key.
Rewriting the key alone leaves the aggregation block carrying one expression
while the projection asks for another, which
SELECT c0 AND (u < 300), count() FROM (SELECT 1::Bool AS c0, 7::UInt8 AS u) t0
GROUP BY c0 AND (u < 300) WITH ROLLUP SETTINGS group_by_use_nulls = 1
reported as `NOT_FOUND_COLUMN_IN_BLOCK`, and which made the same query with a
correlated reference to `c0` bind that reference to a `Nullable` header column by
name only, so the strict `UInt8 -> Bool` conversion cast a `ColumnNullable` to
`ColumnVector<char8_t>` and raised a logical error.
The two `and`-chain sites therefore do not run at a query level whose keys become
Nullable. The condition is tracked per query level rather than per clause because
copies of a key are also planted outside the GROUP BY list: passes registered
earlier resolve `grouping(k)` to a function that retains `k` as an argument, and
replace `min(k)` over a key with a copy of `k`. `OptimizeGroupByFunctionKeysPass`
and `OptimizeGroupByInjectiveFunctionsPass` return for the whole query on the
setting alone; this is the same choice, restricted to the modifiers that make the
keys Nullable and to two of the four sites.
Inside such a query the two optimizations also stop running in `WHERE`,
`JOIN ON` and `HAVING`. That is a plan-quality loss under a non-default setting,
in exchange for a condition that does not depend on enumerating where copies of a
key can appear.
Covers both defects and the two properties the fix rests on. For the substitution: a non-boolean survivor is evaluated as a boolean for a `UInt8`, a `LowCardinality(UInt8)`, a `UInt32` holding 256 and a `Bool` holding byte 2 built with `reinterpret`; the `AND` is kept around it while a survivor that is a boolean function still replaces the `AND` on its own, and the same probe returns the opposite answer with `optimize_redundant_comparisons = 0`, so neither plan assertion can pass vacuously. A `tokenbf_v1` index is still consulted for `hasToken(msg, 'needle') AND (severity < 300)`, which is what keeping the `AND` buys. For the `GROUP BY` key: the key shapes that were rejected or aborted now return values equal to their un-optimized ground truth, with a key whose surviving operand is not always true as the sensitivity control; `grouping()` and `min()` over such a key are pinned because passes that run earlier retain the key expression outside the `GROUP BY` list; and the correlated shapes are pinned at the error they already give when nothing is pruned. The guard's scope is stated both ways: the two AND-chain optimizations do not run in `WHERE` or `JOIN ON` of such a query, each row paired with its `group_by_use_nulls = 0` sibling, while a chain at a nested query level is still optimized. `04032_and_comparison_filter_optimization_2` pins the plan text of this substitution; its one `EXPLAIN SYNTAX` line moves from `notEquals(x, 0)` to `and(x, 1)`. Its value rows, which assert the same invariant its comment states, are unchanged. `enable_analyzer` is pinned because the query-tree explains are analyzer-only: without it the test is red in the old-analyzer stateless lane.
The row asserting that a chain at a nested query level is still optimized filtered on the generic `indexHint` marker. `EXPLAIN SYNTAX` returns the whole plan as a single row, so a hint derived at either query level satisfied it, and the row could not fail in the direction that matters: if the per-level flag were lost on the way back out of a nested level, the outer key that must be left alone would be optimized as well, emit its own hint, and the row would still return one. Its comment justified the missing half by pointing at the preceding row, which is a different query with no nested level and cannot observe that. Replace it with two rows that name the `indexHint` each level derives, read off the printed plan rather than guessed: the nested level's `less(a, 3)` must be present, the outer guarded key's `less(x, 3)` must be absent. Neither pattern contains an internal wildcard, so one level's hint cannot stand in for the other's. A third row repeats the outer pattern with `group_by_use_nulls = 0`, so the absence is attributable to the guard rather than to a pattern that matches nothing. Checked against a build whose `leaveImpl` pops the flag only for `UnionNode`, leaving a nested level's push in place: the outer-hint row goes from zero to one there, while the row it replaces still passes. Add an un-prunable sibling for the correlated `NOT_IMPLEMENTED` rows, which asserted in prose that the rejection also happens when nothing is pruned without any row measuring it. Give the row that contains no `AND`, and therefore has no sole survivor, its own comment instead of leaving it under a claim it does not exercise. Wrap the SQL literals in the comments of both files in inline code blocks; that part changes comment text only, and stripping the comments from both revisions of the pass leaves the two token streams identical.
Internal second-model review (click to expand)An independent model reviewed this change cold against the resulting code, and I adjudicated every
Beyond the findings, I verified rather than accepted the load-bearing claims the diff's own comments Session ids: cron:clickhouse-review-slot-9:20260831-043700, cron:clickhouse-review-slot-11:20260831-062000, cron:clickhouse-review-slot-10:20260831-072100, cron:clickhouse-review-slot-48:20260831-142100, cron:clickhouse-review-slot-9:20260831-224504 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260831-215400 |
|
Workflow [PR], commit [598737a] Summary: ✅
AI ReviewSummaryThe PR fixes boolean normalization when comparison pruning leaves one Missing context / blind spots
Final Verdict✅ Approve. No new inline findings; no existing review thread requires a reply or state change. |
|
cc @yakov-olkhovskiy @novikd, could you review this? The AND comparison-chain optimization installed a sole surviving operand raw whenever its declared type was typeid-equal to the AND's, so |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 15 s compile time in total, 7 of them have a recent master baseline. |
…guard A review question asked whether the guard can be scoped to the clauses a level resolves after GROUP BY, leaving JOIN ON, PREWHERE and WHERE optimized. It cannot, and the reason is not about clause order: an alias makes one query-tree node serve two clauses, so `WHERE k` and `GROUP BY k` are the same node, and moving it while visiting WHERE moves the key. A build that unguards the join tree, PREWHERE and WHERE rejects both queries added here with Code: 10. Not found column __table1.c0 in block __grouping_set UInt64, and(__table1.c0, 1_Bool) Nullable(Bool), count() UInt64 where the block holds the rewritten key and the consumer asks for the bare column. Both spellings of the sharing are covered, a projection alias and a WITH alias. The rows pass on this branch, are rejected on the base commit, and are rejected on that narrowed build, so they fail in the direction a narrowing would introduce and not only in the direction this fix repairs. The cost behind the question is real and stays. With group_by_use_nulls = 1 and ROLLUP, a WHERE that loses its transitive inference reads 123/123 granules where the base commit reads 1/123. The PR description already states that the two optimizations stop running in the other clauses of such a query, and issue ClickHouse#106377 tracks the general answer that would let the guard go away.
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Bugfix validation (functional tests, amd64) |
job-level abort at ci/jobs/functional_tests.py:734, AssertionError: Could not find master builds in S3, before any server starts, so nothing was validated and no test is attributed. Trunk-wide, byte identical on unrelated PRs |
#117433 (mine, open) |
Bugfix validation (functional tests, aarch64) |
same Could not find master builds in S3 abort as the row above |
#117433 (mine, open) |
Finish Workflow / Post Hooks (new_tests_check.py) |
pure cascade of the two rows above: the hook reds when no per-arch bugfix job reports OK or XFAIL, and its own output quotes both aborts | #117433 (mine, open) |
Docs examples / Documentation examples, Function/toYYYYMM#0 |
the example in src/Functions/toYYYYMM.cpp documents SELECT toYYYYMM(now(), 'US/Eastern') as 202608, so it began returning 202609 when the month rolled over in US/Eastern at 2026-09-01 04:00 UTC. Time triggered and trunk-wide: 27 unrelated PRs carry this row within three hours of that boundary, against 0 rows in the preceding 10 days |
#117459 (mine, open) |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
job-level container-memory abort with no failing test assertion: the shard's nested containers breach the /docker cgroup leaf, which ci/jobs/integration_test_job.py then reports. Merging master would not help: #117202 is absent from this head, but the same shard aborts identically on heads that do contain it, so it is not the fix |
#117411 / #117412 (both open) |
Session id: cron:our-pr-ci-monitor:20260901-070000
…in-sole-survivor Master moved the optimize_and_compare_chain derivation into its own JOIN_ON_AND_COMPARE_CHAIN visitor run. The per-query-level group_by_use_nulls guard now applies to the and node in both runs, and the stack is popped before the early return master added to leaveImpl, since both runs push it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…son pruning
Master now lets an AND whose result type is Nothing reach the comparison
pruning (an ARRAY JOIN over an empty array gives a Nothing-typed column).
The sole-survivor path then built the identity constant 1 with type Nothing,
which cannot hold a value, so
SELECT count() FROM numbers(1) ARRAY JOIN [] AS a0
GROUP BY a0 AND (materialize(7::UInt8) < 300)
was rejected with TYPE_MISMATCH while master accepts it. Leaving the AND as
it is matches the precedent for the always-false collapse in the same
function, and gives the result of optimize_redundant_comparisons = 0. The
same JOIN ON shape, which master rejects with INVALID_JOIN_ON_EXPRESSION
because it installs the bare column as the join expression, now succeeds.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in-sole-survivor Master now runs the and/or/equals rewrites post-order from leaveImpl (rewriteFunction) and memoizes shared nodes in visited_nodes. The guard flag moves into a keepAnd() helper so rewriteFunction can read it; the per-query-level stack is still pushed in enterImpl and popped first in leaveImpl, so a function node's rewrite sees its own level's entry. The identifier resolve cache is per query scope, so the memo cannot carry a node from a guarded level into an unguarded one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Also give the GROUP BY smoke row without an AND its own heading, so it no longer sits under the boolean-function survivor comment. Comments only; the reference is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #106377
Related: #117241
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed two defects in the
ANDcomparison-chain optimization. When pruning always-true comparisons left a single operand, that operand replaced the wholeANDwithout being evaluated as a boolean, soSELECT materialize(2::UInt8) AND (materialize(7::UInt8) < 300)returned2instead of1. The same substitution also rewrote aGROUP BYkey without theNullablecopies of it thatgroup_by_use_nullscreates, which rejected a valid query withNOT_FOUND_COLUMN_IN_BLOCKand raised a logical error when a correlated subquery referenced an operand of the key, which is now reported asNOT_IMPLEMENTED.Description
Two defects in one substitution block of
tryOptimizeAndCompareNotEqualsChain, which installs a single surviving operand in place of a wholeANDafter always-true comparisons are pruned.A wrong result, on default settings. The substitution reduced the survivor to a boolean on only one of its three paths: a survivor whose declared type is type-equal to the
AND's was installed raw (DataTypeNumber::equalscompares typeids, soUInt8andBoolboth qualify), and aLowCardinality(UInt8)survivor was merely cast, which preserves the value. A survivor that is a boolean function is now installed as-is; any other survivor keeps theANDand gains a constant1operand, soandperforms the!= 0itself.tryReplaceOrEqualsChainWithInadds a stub0to anorfor the same reason, andtryOptimizeCommonExpressionsInAndalready uses thisand(arg, 1)form. Keeping theANDalso keeps an index atom resolvable, sohasToken(msg, 'x') AND (severity < 300)still consults atokenbf_v1index.A rejected query and a logical error.
registerNullableGroupByKeysstores aGROUP BYkey unwrapped and hands every other resolution of the same expression aNullableclone. Bothand-chain sites decline on aNullableresult, so they moved the key alone, while theorandequalssites rewrite a copy too and restore itsNullablewrapper. Theand-chain sites now do not run at a query level whose keys becomeNullable, tracked per query level because copies of a key are planted outside theGROUP BYlist too.Two costs, both deliberate. With
c0declaredUInt8the correlated query returns1/\Ntoday and will returnNOT_IMPLEMENTED; making it return a value needs #106377. And inside such a query the twoand-chain optimizations also stop running inWHERE,JOIN ONandHAVING.Workflow [PR]
Sync PR [sync-upstream/pr/117427]
Workflow [PR]
Sync PR [sync-upstream/pr/117427]