Skip to content

Fix a wrong result and a rejected query in the AND comparison-chain optimization - #117427

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-and-compare-chain-sole-survivor
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-and-compare-chain-sole-survivor

Conversation

@groeneai

@groeneai groeneai commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #106377
Related: #117241

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):

Fixed two defects in the AND comparison-chain optimization. When pruning always-true comparisons left a single operand, that operand replaced the whole AND without being evaluated as a boolean, so SELECT materialize(2::UInt8) AND (materialize(7::UInt8) < 300) returned 2 instead of 1. The same substitution also rewrote a GROUP BY key without the Nullable copies of it that group_by_use_nulls creates, which rejected a valid query with NOT_FOUND_COLUMN_IN_BLOCK and raised a logical error when a correlated subquery referenced an operand of the key, which is now reported as NOT_IMPLEMENTED.

Description

Two defects in one substitution block of tryOptimizeAndCompareNotEqualsChain, which installs a single surviving operand in place of a whole AND after 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::equals compares typeids, so UInt8 and Bool both qualify), and a LowCardinality(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 the AND and gains a constant 1 operand, so and performs the != 0 itself. tryReplaceOrEqualsChainWithIn adds a stub 0 to an or for the same reason, and tryOptimizeCommonExpressionsInAnd already uses this and(arg, 1) form. Keeping the AND also keeps an index atom resolvable, so hasToken(msg, 'x') AND (severity < 300) still consults a tokenbf_v1 index.

A rejected query and a logical error. registerNullableGroupByKeys stores a GROUP BY key unwrapped and hands every other resolution of the same expression a Nullable clone. Both and-chain sites decline on a Nullable result, so they moved the key alone, while the or and equals sites rewrite a copy too and restore its Nullable wrapper. The and-chain sites now do not run at a query level whose keys become Nullable, tracked per query level because copies of a key are planted outside the GROUP BY list too.

Two costs, both deliberate. With c0 declared UInt8 the correlated query returns 1 / \N today and will return NOT_IMPLEMENTED; making it return a value needs #106377. And inside such a query the two and-chain optimizations also stop running in WHERE, JOIN ON and HAVING.


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


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

…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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent model reviewed this change cold against the resulting code, and I adjudicated every
finding against the source. Five rounds; the entries below are the ones whose verdict is terminal
against the current head. Rows describing an earlier mechanism were restated after the substitution
was redesigned from wrapping the survivor in notEquals to keeping the AND and adding its identity
operand, so the counts and plan assertions below are the ones that hold now. The final round found
nothing.

Finding Verdict
❌ The regression test asserts on EXPLAIN SYNTAX run_query_tree_passes = 1 output but never pins the analyzer, so it is red in the old-analyzer functional lanes. Agreed and fixed. InterpreterExplainQuery ignores run_query_tree_passes when allow_experimental_analyzer is off and formats the old-analyzer AST instead, so neither token the test looks for is ever printed: the checks that assert a token is present read 0, and the ones that assert a token is absent pass for the wrong reason. Two stateless lanes install that setting as a profile default, and nothing in the runner re-enables it outside the cloud path. Fixed by pinning enable_analyzer = 1, which is what the two nearest tests for this bug family and this optimization already do. Verified by running the file with the analyzer forced off both without the pin (fails) and with it (passes); the profile carries no settings constraint, so the pin cannot be refused. The same run showed a pre-existing row in the file was already red in that lane, which the pin also repairs.
⚠️ The new test proves values and error codes but never proves either optimization is still active and correctly scoped. Agreed, fixed over three rounds. Every original assertion was a value or an error code, so the rows meant to show that a boolean-function survivor keeps its plan asserted only its value; every new GROUP BY key carried one comparison, so the guard's effect on the transitive-inference optimization was unexercised; and the two rows for clauses outside the GROUP BY returned the same count either way, so they could not detect scope leakage. The test now asserts the plan: that a non-boolean survivor is left inside an and while a boolean-function survivor stands alone, that the derived indexHint conjunct appears with the setting off but not inside the guarded query level, and that a tokenbf_v1 index is still consulted for an atom next to an always-true comparison. Every absence assertion carries a control that makes the absence attributable: a sibling row flipping the setting responsible for it, or, for the one row with no such sibling, the same probe asserting a presence on the same query.
⚠️ The nested-query-level probe cannot fail when the outer, guarded GROUP BY key is the one that gets optimized: the query holds two independently optimizable comparison chains and the oracle filters on the generic indexHint marker, so a hint from either level satisfies it. Agreed and fixed. The scenario is reachable, not hypothetical: where_child_index is 4 and group_by_child_index is 5 in QueryNode.h and children are visited in index order, so a nested query in WHERE is visited before the outer key, and a one-line change that drops the level's flag on the way out optimizes the outer key while the row still reads 1. The row now asserts the inner level's hint is present and the outer level's is absent, each pattern naming the conjunct its own level derives and read off the printed plan rather than guessed, so neither can stand in for the other. The absence probe has a group_by_use_nulls = 0 sibling, so a pattern that matches nothing cannot pass for a guard that worked, and it was shown to change answer on a build carrying that one-line change while the row it replaces still passed. The comment that justified the unmeasured half by citing the preceding row was removed: that row is a different query with no nested level, so it cannot detect a fault only a nested level can cause.
💡 Literal SQL and type names are left outside inline code in two of the three added comment blocks and in the new test's comments, and one comment writes grouping() where the repository asks for grouping. Agreed and fixed for the type names, function names and SQL keywords the added comment lines carry. The repository asks for literal names from the SQL language, classes and functions in inline code, and for a function written as f rather than f(); the rule predates this branch's base. The diff was inconsistent with itself, since a third added block and all three commit messages already backtick the same tokens. Measured over added comment lines before the fix: AND bare 6 times, Nullable 6, GROUP BY 4. Only the lines this change adds were touched. Two prose mentions of a setting name in the test's comments are still bare, which is the residual this leaves.
💡 The rows asserting that a correlated reference is rejected claim the shape behaves "as it is when nothing is pruned", but no row measures the un-prunable variant. Agreed and fixed. Every other absence or rejection claim in the test is paired with a control, so this was the one unpaired claim, and without it a reader cannot tell a pre-existing rejection from one this change introduces. The un-prunable correlated shape is now asserted alongside them.
💡 A comment about a boolean-function survivor heads a row that contains no AND, and so no survivor. Agreed and fixed for the row the finding names. Traced in the source: tryOptimizeOutRedundantEquals declines c0 = true because the replacement is a ColumnNode rather than a boolean FunctionNode, and declines u = 7 because the constant exceeds 1, while the or chain is shorter than optimize_min_equality_disjunction_chain_length. The row is a useful smoke case for a guarded level whose or and equals sites stay active, so it was relabelled rather than removed. The smoke row above it holds no AND either and still sits under that heading.
💡 Two of the added comment blocks are long. Disagreed. Each states why a non-obvious property holds, which is the kind of comment this project asks for; none of them refers to the fix, a measurement or a rejected alternative. Across the current diff there are 8 added comment lines against 21 added lines of code in src/, with two comment blocks removed. The separate style point above was agreed and fixed; it is about how identifiers are written, not about which comments exist.

Beyond the findings, I verified rather than accepted the load-bearing claims the diff's own comments
make, and found them correct: that the substitution preserves the node's result type in every
reachable case, because and returns Bool exactly when one of its arguments is Bool and the
surviving operand is one of the original arguments, so it is Bool whenever the AND was, while the
operands this block prunes are always comparisons and never Bool; that and cannot widen a result
to LowCardinality, since it declines dictionary execution; that the new per-level condition is the
same expression the analyzer itself uses to decide when a key becomes Nullable; that the push and
the pop of that per-level state are paired unconditionally by the base visitor, which also installs
the query node's own context before the push, so the flag is that level's; and that the or and
equals rewrite sites restore the Nullable wrapper and keep the rewritten key as a subterm, which
is why they are correctly left untouched. Typing the added constant as the AND's own result type is
belt and braces rather than load bearing: a build that types it a bare UInt8 moves nothing across a
twelve-case probe, because of the argument above. The JOIN ON optimizer visitor was checked as a
route into the two guarded rewrites and calls neither of them.

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

@clickhouse-gh clickhouse-gh Bot closed this Aug 31, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, single commands, 100% on the base build 078e0ea5. Wrong result: SELECT materialize(2::UInt8) AND (materialize(7::UInt8) < 300) returns 2. Rejected valid query: SELECT c0 AND (u < 300) AS k, 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 returns Code: 10 NOT_FOUND_COLUMN_IN_BLOCK. Logical error: the same query with (SELECT c0) in the projection exits 134 with Bad cast from type DB::ColumnNullable to DB::ColumnVector<char8_t>. None of the three is a rate.
b Root cause explained? Yes. tryOptimizeAndCompareNotEqualsChain prunes always-true comparisons and replaces the whole AND with the single survivor. It reduced that survivor to a boolean on only one of three paths: a survivor whose declared type is type-equal to the AND's was installed raw (DataTypeNumber::equals compares typeids, so UInt8 and Bool both qualify) and a LowCardinality(UInt8) one was merely cast, which preserves the value. Separately, registerNullableGroupByKeys stores a GROUP BY key unwrapped and gives every other resolution of the same expression a Nullable clone; both and-chain sites decline on a Nullable result, so under group_by_use_nulls with ROLLUP, CUBE or GROUPING SETS they moved the key alone and the aggregation block then carried one expression while consumers asked for another.
c Fix matches root cause? Yes, and each half addresses one defect. A survivor that is a boolean function is installed as-is; any other survivor keeps the AND and gains a constant 1 operand, so and performs the != 0 itself, the and(arg, 1) form already used by tryOptimizeCommonExpressionsInAnd, and the stub-constant shape tryReplaceOrEqualsChainWithIn uses for or. The two and-chain sites then do not run at a query level whose GROUP BY keys become Nullable, which is a property of the level rather than an enumeration of where copies of a key live. No widened bound, no no-random-* tag, no reduced dataset, no guard at the abort site.
d Test intent preserved / new tests added? No existing test was weakened or deleted. One new test, 05066_and_compare_chain_sole_survivor, 47 reference lines covering both defects, the boolean-survivor invariance, the skip-index atom, grouping and min over the guarded key, the guard's clause scope with its group_by_use_nulls = 0 controls, and a nested query level in both directions (the nested chain IS optimized, the outer guarded key is NOT). 25 of those lines have a demonstrated reddening arm across a 9-arm build-id-asserted matrix; the rest are stated as invariance pins or discriminating controls, not as oracles. Each row that asserts an ABSENCE is paired with a control that makes the absence attributable: three group_by_use_nulls = 0 siblings, one optimize_redundant_comparisons = 0 sibling, the u < 5 un-prunable sibling of the NOT_IMPLEMENTED rows, and the same-pattern-unguarded sibling of the outer-hint row. One line of 04032_and_comparison_filter_optimization_2.reference is updated because it pins the EXPLAIN SYNTAX text of exactly this substitution (WHERE notEquals(x, 0) becomes WHERE and(x, 1)); its value rows and every other row are untouched, and the invariant its comment states still holds.
e Both directions demonstrated? Yes. 05066 FAILS on base 078e0ea5 and PASSES on the fix ad4051dd, each server's SELECT lower(buildId()) asserted against its ELF note before the run, and 50/50 with runner randomization on. Every value reported is a base-vs-fix pair, with the un-optimized behaviour (optimize_redundant_comparisons = 0) as an independent ground truth, and a sensitivity control (u < 5, so nothing is pruned) that is identical on all arms. Beyond base-vs-fix, each oracle that could only fail in one direction was also put against a targeted mutant of the fix itself, so its live direction is exhibited rather than argued.
f Fix is general across code paths? Yes, and the enumeration closes on a property instead of a list: at a query level whose keys become Nullable, neither and-chain site rewrites anything, so no copy of such a key (planted by any earlier pass, in any clause, at any depth) can be moved by them. That is what the previous, clause-scoped attempt could not promise: GroupingFunctionsResolvePass and AggregateFunctionOfGroupByKeysPass run earlier and retain the key expression outside the GROUP BY list, and both cases are now pinned. The or and equals sites repair the Nullable wrapper and move a key together with its copies, so they are deliberately untouched. For the substitution itself, the sibling sites in the same file were enumerated and probed: tryReplaceOrEqualsChainWithIn (stub 0, already correct), tryOptimizeOutRedundantEquals (refuses a non-boolean replacement), and the two tryOptimizeCommonExpressionsIn* sites, where nine probe shapes produced no reaching input and no wrong result.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured over UInt8, Bool, LowCardinality(UInt8), UInt32 holding 256, a Bool holding byte 2 built with reinterpret, a Float64 operand, and constant Float64 / Int64 / UInt64 survivors. Nullable cannot reach the block (chassert(!function_type->isNullable()) plus the isNullable declines). Modifier matrix: WITH ROLLUP, WITH CUBE, GROUPING SETS, and plain GROUP BY as the negative case, each with group_by_use_nulls 0 and 1. Plan preservation is asserted and not only result correctness: a boolean-function survivor keeps a byte-identical query tree, and the same probe returns the opposite value with the optimization off, so the assertion is not vacuous.
h Backward compatible? Yes. No setting added or re-defaulted, no serialization or format change, no deletion path, nothing experimental to gate, so no SettingsChangesHistory.cpp row is required. Two behaviour changes are disclosed in the description: with c0 declared UInt8 the correlated query returns a value today and will return NOT_IMPLEMENTED, and inside a group_by_use_nulls query with one of those modifiers the two and-chain optimizations also stop running in WHERE, JOIN ON and HAVING.
i Invariants and contracts preserved? The invariant is that whatever replaces an AND evaluates its operand as a boolean, which the identity operand discharges for every operand type without a truncating cast. The per-query-level flag is pushed in enterImpl before any early return and popped as the first statement of leaveImpl, above the optimize_extract_common_expressions return, and the base visitor calls the pair unconditionally, so it cannot underflow or drift; the whole case matrix re-run with that setting off is byte-identical, and a deep case nesting a modifier level inside a UNION ALL inside a subquery behaves the same. getSettings() in enterImpl reads the query node's own context, which the visitor installs before the call. No lock, no allocation in a hot loop, no new error path, nothing persisted.

Session id: cron:clickhouse-impl-slot-41:20260831-215400

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [598737a]

Summary: ✅


AI Review

Summary

The PR fixes boolean normalization when comparison pruning leaves one AND operand, and prevents asymmetric rewrites of nullable GROUP BY keys. No actionable findings remain at 598737aed07bc592f2d72efe5c000b327f404e92. The existing thread's query-scope tradeoff is justified by shared aliases and covered by regression tests. Consumers checked for the retained and(arg, 1) representation include function resolution and execution, planner action construction, and primary-key and text Bloom-filter condition builders; these handle the logical node and identity constant without hiding the surviving index atom.

Missing context / blind spots
  • ⚠️ No local executable or configured build was available, so tests were not rerun locally. Assessment uses the committed regression tests, the author's documented validation, and published CI results. Running 05066_and_compare_chain_sole_survivor and 04032_and_comparison_filter_optimization_2 on the current head would provide independent runtime confirmation.
Final Verdict

✅ Approve. No new inline findings; no existing review thread requires a reply or state change.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d880121]

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 SELECT materialize(2::UInt8) AND (materialize(7::UInt8) < 300) returned 2 on default settings, and the same substitution rewrote a GROUP BY key without the Nullable copies that group_by_use_nulls creates.

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 598737aed with master f30d7ec4f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 15 s compile time in total, 7 of them have a recent master baseline.

Job report

…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.
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a27d7145482ec43f1f88038913acc7398113e78e

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link I
will post here when it opens.

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

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
groeneai and others added 4 commits October 20, 2026 11:50
…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]>

This branch has not been deployed

No deployments
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-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant