Skip to content

Fix wrong results and NOT_FOUND_COLUMN_IN_BLOCK when a GROUP BY key comparison is an operand of an OR or AND chain - #125846

Open
groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:fix-group-by-key-in-logical-chain-rewrites
Open

groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:fix-group-by-key-in-logical-chain-rewrites

Conversation

@groeneai

@groeneai groeneai commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fix NOT_FOUND_COLUMN_IN_BLOCK and wrong results when a comparison that is a GROUP BY key is also an operand of an OR or AND chain, for example SELECT (x = 1) OR (x = 2) OR (x = 3), count() FROM t GROUP BY x = 1, x = 2, x = 3. With GROUP BY ROLLUP(x, x = 1) such a chain returned a wrong value on the rows where x = 1 is rolled up.

Description

Related: #125803
Related: #125828 (other passes).

On 26.8.18.2 and 26.3.42.3, SELECT (x = 1) OR (x = 2) OR (x = 3) AS e, count() FROM (SELECT number % 4 AS x FROM numbers(8)) GROUP BY x = 1, x = 2, x = 3 throws NOT_FOUND_COLUMN_IN_BLOCK, and with GROUP BY ROLLUP(x, x = 1) such an OR returns a wrong value where x = 1 is rolled up.

After GROUP BY an expression equal to a key is read from the aggregation result. LogicalExpressionOptimizerPass rewrote a key operand like any comparison: merged into IN/NOT IN, folded, used to derive conjuncts, or flattened into the enclosing and. The result then needs x, gone after aggregation (or, in a ROLLUP, rolled up differently).

Before rewriting a query level, the pass now records its comparison and and nodes that equal a GROUP BY key (under group_by_use_nulls ignoring types, as a copy after GROUP BY can be Nullable at any level), then keys sharing a node with them; neither it nor a function below it is rewritten, as copies could differ, nor merged as an operand, and the compare chain neither flattens through it nor derives a conjunct onto an operand containing one. Master still fails after #123925, also with enable_identifier_resolve_cache = 0.

Trade-off: a key comparison is no longer rewritten or used for inference in its query level (also in WHERE); column keys are unaffected. EXPLAIN QUERY TREE with 51 keys and a 2000-operand OR: 218 vs 215 ms.

The new test fails on master and passes 30/30 with randomized settings; 102 of 105 related tests and 76 of the 77 group_by_use_nulls tests pass (the others fail without it too). 05394 now expects no derivation into a bare and key. LIKE chains (ConvertOrLikeChainPass): #125894.

🤖 Generated with Claude Code


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

After `GROUP BY`, the planner reads every expression equal to a key from the
aggregation result; the inputs of a key are gone unless they are keys too.
`LogicalExpressionOptimizerPass` runs after the analyzer has resolved such
expressions, and it treated a key operand of an `or`/`and` chain as an ordinary
comparison:

- `(x = 1) OR (x = 2) OR (x = 3)` was merged into `x IN (1, 2, 3)`,
- `(x != 1) AND (x != 2) AND (x != 3)` into `x NOT IN (...)`,
- `(x > 1.5) AND (x < 3.5)` was folded to `x >= 2 AND ...`, and
  `(x >= 1) AND (x != 1)` strengthened to `x > 1`,
- the compare chain derived `t1.a = 4` from `t1.a = t2.b AND t2.b = 4` and
  flattened a nested `and` key into the enclosing `and`,

even when each of those comparisons was itself a `GROUP BY` key. The
rewritten expression then needs `x`, which does not exist after aggregation
(`NOT_FOUND_COLUMN_IN_BLOCK` at default settings), or, when `x` is another
key of a `ROLLUP`, it recomputes the rolled-up key from `x` and returns a wrong
value on the rows where that key is rolled up.

The pass now records, per query level and before rewriting it, the comparison
and `and` nodes equal to a `GROUP BY` key (or to its `Nullable` shape under
`group_by_use_nulls` with ROLLUP/CUBE/GROUPING SETS, as
`OptimizeLimitByInjectiveFunctionsPass` does), compared with
`compareGroupByKeys`. The three rewrites keep such a node as written, and the
compare chain neither flattens a nested `and` through it nor derives a
conjunct onto an operand that contains one: the derived conjunct would hold a
clone of the key node that is not recorded, and the `OR` inside it would still
be merged. The nodes are recorded first because the pass rewrites `or`/`and`
nodes inside a key in place: once the `GROUP BY` clause is visited,
`if((x = 1) OR (x = 2) OR (x = 3), x, 0) = 1` is `if(x IN (1, 2, 3), x, 0) = 1`,
and a copy in `HAVING` would no longer equal it. The rule applies to every
clause of the level, because one node can be shared by several clauses.

Operands that are not keys are still merged (`GROUP BY x, y = 0` and
`ROLLUP(x, x = 1)` with four `=` keep producing `in`).

Related: ClickHouse#125803

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

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

Pre-publication review by an independent model (engine: codex; 3 rounds, 4 findings, the last round clean) plus my own cold reviews (4 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ A key whose subtree holds an or/and the pass rewrites is changed in place when GROUP BY is visited, so its copy in HAVING/ORDER BY no longer compared equal and was still merged AGREE, fixed key nodes are recorded by pointer before the level is rewritten; HAVING test row
2 ⚠️ One and key disabled nested-and flattening for every chain of the query AGREE, fixed flattening stops only at an and that is a key; plan-shape control row
3 ❌ The compare chain clones an operand into a derived conjunct; a key node inside the clone is not recorded, so its OR was still merged (JOIN + HAVING, NOT_FOUND_COLUMN_IN_BLOCK) AGREE, fixed no derivation onto an operand that contains a key node; JOIN/HAVING test row + control that derivation onto a key-free operand still happens
4 💡 Key enumeration also exists in #125828 AGREE, noted #125828 is unmerged; the description names it
5 💡 Related references not one full URL per line AGREE, fixed description
6 💡 The same level walk is written twice (collectGroupByKeyNodes, containsAnyOf) AGREE, noted style only

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-self-slot-58:20261014-182100

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3da1448]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

The PR preserves GROUP BY key expressions and their shared descendants during logical rewrites, preventing missing-column exceptions and incorrect subtotal values. No actionable findings remain after reviewing the current diff and every prior thread. Both regression tests (05397 and the 05394 budget sweeps) match their references on the PR's CI binary. Hash collection adds no measurable planning overhead for the reported 50-, 100-, and 200-operand workload. The previously deferred nullable-key issue is addressed by merged PR #131726, and its reproducer returns the expected rows on the CI merge build.

Final Verdict

Status: ✅ Approve

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test fails on every run against master (return code: 10); 11 of its statements throw NOT_FOUND_COLUMN_IN_BLOCK and 3 return wrong values at default settings.
b Root cause explained? Yes. After GROUP BY an expression equal to a key is read from the aggregation result. LogicalExpressionOptimizerPass merged, folded or extended a key comparison (or flattened an and key) as if it were an ordinary operand, so the result needed the key's input column, which is gone after aggregation or, in a ROLLUP, has a different rollup.
c Fix matches root cause? Yes. The three chain rewrites keep an operand equal to a GROUP BY key of the same query level as written (compareGroupByKeys), and the compare chain does not flatten through an and key. No setting, no tag.
d Test intent preserved / new tests added? Yes. New test: 14 statements that fail on master, plus 7 EXPLAIN controls that fail an over-blocking fix (operands that are not keys must still be rewritten, and an unrelated nested and must still be flattened).
e Both directions demonstrated? Yes. Master build: [ FAIL ]; fixed build: [ OK ], 50/50 with randomized settings, and also with enable_identifier_resolve_cache = 0.
f Fix is general across code paths? Yes. All three rewrites of the pass (OR to IN; the AND chain: NOT IN, folding, pruning; the compare chain incl. flattening, which also no longer derives a conjunct onto an operand that contains a key node). tryOptimizeOutRedundantEquals, the WHERE/PREWHERE common-expression extraction and the JOIN ON visitor rewrite every copy the same way or run before aggregation.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Nullable key copies under group_by_use_nulls with ROLLUP/CUBE/GROUPING SETS, LowCardinality, LowCardinality(Nullable), a Nullable column, GROUP BY ALL, aliases, subqueries and JOIN keys; HAVING, ORDER BY, window, QUALIFY and LIMIT BY uses match the output with the rewrites disabled.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only results that were wrong or rejected change. Queries grouping by columns keep their rewrites.
i Invariants and contracts preserved? Yes. The per-query key stack is pushed in enterImpl and popped first in leaveImpl, so it stays balanced whatever optimize_extract_common_expressions is; the key nodes are recorded by pointer before the level is rewritten, so a copy still matches after the pass rewrites an or/and inside it.

Session id: cron:clickhouse-impl-self-slot-57:20261014-155600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @yakov-olkhovskiy, could you review this and add can be tested (I cannot set labels right now)? LogicalExpressionOptimizerPass merged, folded or derived conjuncts from a comparison that is also a GROUP BY key, so the rewritten expression needed the key's input column, which is gone after aggregation; the pass now records such key nodes before rewriting a query level and keeps them as written.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 14, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 15, 2026
The key and each of its copies after `GROUP BY` were rewritten one by
one, and the rewrites can treat equal copies differently: a
`group_by_use_nulls` copy is `Nullable`, a redundant `(x = 1) = 1` is
replaced by an unrecorded `x = 1` that a parent shared with
`ORDER BY ALL` or a `HAVING` alias then merges into `in`, and the
compare-chain hash budget can run out between copies. Then a copy no
longer matches the key and needs its input column
(`NOT_FOUND_COLUMN_IN_BLOCK`). Keep every recorded key node as written.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…writes

Skipping only the recorded key node still let its descendants be rewritten,
and the copies of a key do not always get the same descendant rewrites: a
projection node shared with `ORDER BY ALL` is visited twice, so a node that a
first visit produced (`(a AND b) = 1` -> `a AND b`) is optimized only on the
second one. The projection copy then gained an `indexHint` that the GROUP BY
key did not, which threw NOT_FOUND_COLUMN_IN_BLOCK, and under ROLLUP silently
recomputed the subtotal rows.

The functions and subqueries below a recorded key copy are now recorded too,
and the visitor does not enter them from any path, so a node shared with the
rest of the query (an alias) stays the same in every copy. Column nodes are not
recorded: they are never rewritten, and they are shared with WHERE, where the
derivations must still happen.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a9b85d3

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 05332_autopr_min_bytes_per_replica_events flaky, not from this PR (it changes only LogicalExpressionOptimizerPass; the test came from master via #120884, 8 hours old): the second min_bytes_per_replica = 500000 run built a probe plan again instead of being rejected at the remembered boundary; passed 133/133 reruns and in 7 other jobs on this head a fix task is created (investigating at full effort, fixing-PR link to follow here)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the rows above a fix task is created (the one for the first row)

CIDB has no other FAIL or ERROR row from the finished run on this head.

Session id: cron:our-pr-ci-monitor:20261016-020005

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05332_autopr_min_bytes_per_replica_events created: #126189

groeneai and others added 2 commits October 30, 2026 11:54
…-logical-chain-rewrites

# Conflicts:
#	src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp
This PR keeps a comparison or `and` that is a GROUP BY key as written, so
the compare chain no longer derives a conjunct into the bare `and` key of
05394 or its SELECT alias copy: the large-budget control now reads 0
(master: 2). Its budget sweep then no longer reaches the all-or-nothing
revert of the compare chain, so the same sweep and control are added for
the key wrapped in `toUInt8`, where the `and` is still copied between the
alias and the key but is not a key itself.

Measured: the new rows give the same output on master and on this PR; on
a build with `revertAndCompareChainIfBudgetExceeded` disabled the wrapped
sweep reports 20 budgets that derive into only one copy (the unwrapped
sweep passes there).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`tryExtractCommonExpressions` replaced each `and` argument of the input
`or` with its flattened copy, in place. With `enable_identifier_resolve_cache`
the `WHERE` condition and a `GROUP BY` key can be the same node while the
`SELECT` copy is separate, so the `WHERE`-only extraction changed the key
and not its `SELECT` copy, and the query failed with
`NOT_FOUND_COLUMN_IN_BLOCK` (or returned wrong `ROLLUP` subtotals).

This PR keeps an `and` GROUP BY key unflattened, so it exposed this for
`SELECT <and of or of nested and> AS e ... WHERE e GROUP BY e`, which master
answers. Master fails the same way for keys whose nested `and` the earlier
rewrites leave alone, e.g. `IN`/`startsWith` conjuncts.

The loop now reads the flattened copy without storing it; the hunk is the
same as the one in ClickHouse#123925.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 3da1448f4b4751715e414dad6c0172835b377289 was not compared: the CI logs cluster did not answer (the endpoint never became ready: the readiness probe timed out: HTTPSConnectionPool(host='t6h0zvqlg…).

See the job log for details.

`collectGroupByKeyNodes` compared every comparison and `and` node of the
query, the keys themselves included, with every key, so a query with K
such keys took O(K^2) structural comparisons, twice (both visitor modes
collect). On a debug build `EXPLAIN QUERY TREE passes=42` of
`SELECT count() FROM numbers(1) GROUP BY number = 0, ..., number = 3999`
spent 4.3 s in this pass (master: none).

The keys are now indexed by a hash that skips column sources, a node is
compared only with the keys of its bucket, and a node shared by several
parents is classified once. `getTreeHash` is not used for the index: it
hashes each column's source in full (all of a subquery source) and counts
towards `optimize_and_compare_chain_max_hash_work`. The keys are
enumerated with `getGroupByKeys`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits October 30, 2026 15:49
The fourth sweep added to 05394 for an `and` below a GROUP BY key made the
test about 38% slower (122 more queries and two more client runs), and the
flaky check under ASan went over its 180 s limit (5 of 29 runs at 180-187 s).

With this PR the original query derives nothing at any budget, so master's
third sweep on it can no longer fail. Redefine the query to the `toUInt8`
wrapped form before that sweep instead, so master's own sweep and final
check exercise the derivation, and drop the extra sweep. The diff to the
master test stays additions only.

Measured with 40 runs at 60 parallel copies on an ASan server: master's
version 10.31 s, previous head 14.28 s, this version 10.83 s (+5%). The
negative control (budget revert disabled) still fails the sweep
(20 0 / 102 1); the master binary still fails the new control row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… key

With `enable_identifier_resolve_cache = 1`, an alias used both as a key and
inside another key resolves to one shared node: in
`GROUP BY e, if(e, x, 0) = 1` the `or` key `e` is the same node as the `e`
inside the comparison key. `collectGroupByKeyNodes` recorded that node as a
descendant of the comparison key, so the `GROUP BY` copy of `e` was kept as
written, while its separate SELECT copy was not a recorded key (only
comparison and `and` keys were matched) and became `in(x, ...)`. The copies
no longer matched after aggregation: `NOT_FOUND_COLUMN_IN_BLOCK`, or wrong
`ROLLUP` subtotals. Master rewrites both copies, so this was a regression of
this PR.

Now any other key that contains a recorded node is matched as a key too,
with all its copies, repeating until no key is added. The walk checks a
node's hash only when its function name is a key's.

Measured with the cache on: the reviewer's query, its `ROLLUP` form with and
without `group_by_use_nulls`, a `toUInt8`-wrapped `and` key, a `WHERE`
alias, a second derived key and `GROUPING SETS` now equal master and the
cache-off result. 93 probe and test files run under `clickhouse local` give
identical output to the previous head (cache 0 and 1) except those 8.
Planning time with 1000-4000 keys (comparison keys, mixed keys, keys sharing
a node through the cache) is unchanged.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 65d5224

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test / 05453_webterminal_close_at_binary_format_question flaky, not from this PR (its diff is LogicalExpressionOptimizerPass and its tests): 05394_executable_pool_does_not_keep_closed_connection_open started /bin/sh (pid 134977) 0.14 s after this test's web terminal session opened, and the embedded client finished only when that pid was reaped about three minutes later, so the test hit its 60 s timeout; the same test failed on 18 other PRs and on master since 2026-10-27 #126995 (mine, open)
Finish Workflow, Mergeable Check, PR praktika rollups of the row above; the 108 later jobs were dropped after that failure #126995 (the owner of the row above)

Session id: cron:our-pr-ci-monitor:20261030-183004

@fm4v

fm4v commented Nov 14, 2026

Copy link
Copy Markdown
Member

@groeneai pull master and fix CI

…-logical-chain-rewrites

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

Copy link
Copy Markdown
Collaborator Author

Merged master into the branch in d30e23a: no conflicts, and the PR's own diff is unchanged. The only red on the previous head, Fast test 05453_webterminal_close_at_binary_format_question, is the web terminal hang fixed by #126995, which this merge brings in. On the merged build 05397 and 05394 pass, including 30 randomized runs. CI is running on the new head; I'll fix anything in it that comes from this PR.

groeneai and others added 2 commits November 14, 2026 13:07
…-logical-chain-rewrites

Conflict in LogicalExpressionOptimizerPass.cpp with ClickHouse#123925, which moved the
OTHER_REWRITES rewrites from enterImpl to leaveImpl and added visited_nodes.
needChildVisit checks the GROUP BY key nodes before visited_nodes, and
leaveImpl does not rewrite a key node, as enterImpl did before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`getGroupByKeyHash` hashed a constant with `updateHashFast`, i.e. by its raw
bytes, while `ConstantNode::isEqualImpl` compares with `compareAt`, which
treats every NaN as equal. A projection copy of a key such as
`x = reinterpretAsFloat64(0x7ff8000000000000)` that uses another NaN payload
landed in a different bucket, was never matched by `compareGroupByKeys`, and
the OR chain rewrite merged it into `x IN (...)`, which needs `x` after
aggregation: NOT_FOUND_COLUMN_IN_BLOCK at default settings.

The planner names a constant by the same text (`getValueName`), so keys it
reads as one column now hash the same. `-0.` and `0.` still hash differently,
but such a pair already fails in the planner with the rewrite disabled.
Planning cost of EXPLAIN QUERY TREE with 1000-4000 comparison keys (integer and
float constants) is unchanged.

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

Copy link
Copy Markdown
Collaborator Author

Merged master again in 8f8f71b: the previous merge missed #123925, which conflicts in LogicalExpressionOptimizerPass.cpp. Its rewrites now run in leaveImpl, so leaveImpl skips the GROUP BY key nodes as enterImpl did before; ed33262 on top fixes the NaN case from the latest review.

groeneai and others added 4 commits November 14, 2026 14:49
With `group_by_use_nulls` and ROLLUP/CUBE/GROUPING SETS, a copy of a key
after GROUP BY is not always the key with only its root converted to
Nullable: when a key also contains another key (`e` and `e = 1`, or `x`
inside `e`), the analyzer can leave the copy with Nullable nodes inside it.
The planner still reads such a copy from the aggregation result, because
it matches it to the key by name, and names do not depend on types. The
root-only `Nullable` clone did not match it, so the copy was rewritten
(for example `or` into `in(nullable_x, ...)`) while the protected key was
not, and the copy was then recomputed from the rolled-up input column:

    SELECT (x = 1) OR (x = 2) OR (x = 3) AS e, count()
    FROM (SELECT number % 4 AS x FROM numbers(8))
    GROUP BY GROUPING SETS ((e, e = 1), (x))
    ORDER BY ALL
    SETTINGS group_by_use_nulls = 1, enable_identifier_resolve_cache = 1;

returned `e = 1` for three rows of the `(x)` grouping set instead of NULL.
Master returns the same wrong rows. Under `group_by_use_nulls` with a
modifier the key lookup now compares the trees ignoring result types,
which replaces the `Nullable` clone of each key. The hash already ignores
types, so the lookup stays a bucket lookup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…5397

The new key lookup ignores types only under group_by_use_nulls with a
modifier; this control fails if that path stops rewriting operands that
are not keys (0 `in` nodes instead of 1).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Under `group_by_use_nulls` with ROLLUP/CUBE/GROUPING SETS, a key copy after
`GROUP BY` can have `Nullable` nodes inside a lambda body, for example
`arrayExists(v -> (v > x) AND ((x = 1) OR (x = 2) OR (x = 3)), [4])` with a key
`e = 1` sharing `e` through the identifier resolve cache. `isEqualExceptTypes`
compared a lambda with the strict `isEqual`, so the projection copy did not
match the protected key, its OR chain became `in(nullable_x, ...)`, and the
`(x)` grouping set returned values recomputed from `x` instead of NULL.

Walk lambda nodes like functions: `LambdaNode::isEqualImpl` compares nothing
itself, the arguments node compares names only, and the body is then compared
ignoring types. Master returns the same wrong rows (it has no key guard).

Lambdas over a Nullable array argument (`arrayExists(v -> ..., [x])`) stay
wrong, also on master and with every rewrite of this pass disabled, so that
is not this pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…_nulls in 05397

A non-key OR chain inside a lambda is still rewritten to `in` while a key
copy inside another lambda is protected: 1 `in` with 4ac3063, 2 before
it (the key copy is rewritten too), 0 with the rewrite disabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`collectGroupByKeyNodes` re-walked the whole query and re-scanned every
remaining key after each propagation step, so keys that share nodes only
pairwise through the identifier resolve cache (`GROUP BY x0 = 0,
bitXor(x0, x1), bitXor(x1, x2), ...`) took one full pass per key:
quadratic planning time even without any chain to rewrite.

Now the query is walked once to index the possible key copies by hash,
each other key's function nodes are indexed to the keys containing them,
and keys are processed from a work queue: a key protects its copies, and
every newly protected function node queues the other keys that contain
it. The collected node set is the same as before.

Measured on a debug build, `EXPLAIN QUERY TREE passes=40` vs `passes=41`
(pass 41 = LogicalExpressionOptimizer), median of 3, identical trees:
the reviewer's overlap query with 2000 keys 0.60 -> 7.93 s before,
0.70 -> 0.71 s now (4000 keys: 0.96 -> 0.99 s); its `ROLLUP` form with
`group_by_use_nulls` 0.67 -> 7.88 s before, 0.71 -> 0.68 s now. 2000
comparison keys, 2000 projection copies, 2000 non-comparison keys and
1000 keys sharing a 400-node alias add no measurable time, as on master.
A probe corpus of 93 files gives byte-identical output to the previous
head with the cache on and off.

`05397` gets a query whose last key is reached only on the second
propagation step; a build that stops after the first step fails it with
`NOT_FOUND_COLUMN_IN_BLOCK`, while master and this build return the
expected rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The flaky check runs a changed test 50 times on parallel workers that
contend only with each other, and 05394 sends 368 statements per run.
Its master version already averaged 131.7 s there (ClickHouse#125735), and the
PR's copy failed 2 of 50 runs at 182-183 s with the other 48 averaging
126.9 s, so any PR touching it is a coin flip against the 180 s limit.
On master it also averages 175.6 s per run in the `amd_msan` parallel
job.

`long` is the exemption `tests/clickhouse-test` documents for this case;
the test now runs 5 times instead of 50 in the flaky check and is skipped
by Fast test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp
@fm4v

fm4v commented Nov 18, 2026

Copy link
Copy Markdown
Member

Merged origin/master (it was conflicting) in ecb1c30. The conflict came from #131479 and #131361 in LogicalExpressionOptimizerPass.cpp:

  • tryOptimizeAndCompareChain now reads its operands through collectFlattenedLogicalArguments instead of getFlattenedLogicalExpression, so the keep_whole set (the GROUP BY key nodes) moved to collectFlattenedLogicalArguments, and getFlattenedLogicalExpression is back to master's signature (nothing else passed keep_whole).
  • The derived-conjunct condition keeps this PR's !containsAnyOf(left.node, group_by_key_nodes_stack.back()) check and master's equal_funcs[key_of(left.node)] lookup.

About the red Finish Workflow: no test failed. The only failing step is can_be_merged.py --review-threads (REVIEW_THREADS_GATE: blocked by unresolved review threads). The full CI suite was skipped because of the one open thread on LogicalExpressionOptimizerPass.cpp (the nullable standalone or key with GROUPING SETS). The author's reply defers that case to #131726 (still open). A reviewer has to resolve the thread, or that PR has to land first, before full CI runs here. The previous full run, on 4f01dd1, only failed 05394_optimize_and_compare_chain_budget_alias_copies with "Test runs too long (> 180s)" in the ASan flaky check, which fa44adc already handles by tagging the test long.

Master enabled `modernize-use-nodiscard` in `.clang-tidy`, so `Build (arm_tidy)` rejects the helper this PR adds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fm4v

fm4v commented Nov 18, 2026

Copy link
Copy Markdown
Member

@groeneai master is merged (ecb1c3083fc) and the PR is mergeable, but the Review Threads gate is still closed by the unresolved thread on src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp ("Protect standalone nullable or grouping keys too"), so the full CI was skipped. You moved that case to #131726. Please either handle it here, or reply in the thread with the link to #131726 and resolve it, so the full CI runs.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I can't resolve that thread: it was opened by clickhouse-gh, and @ Algunenano asked me not to resolve those (#130279 (comment)). The bot resolves its own threads once the issue no longer holds, and on this branch it holds until #131726 is merged. The case is pre-existing (the bot also reproduced it on the base 8447a0ec294f), and the link to #131726 is already in the thread (#125846 (comment)). Could you resolve it, so the full CI runs?

alexbakharew pushed a commit to aschoube/ClickHouse that referenced this pull request Nov 19, 2026
With `enable_identifier_resolve_cache` (the default), every reference to
an identifier inside a GROUP BY key resolves to the same node, so a key
such as `if((x = 1) OR (x = 2), 'a', 'b')` grouped together with `x` holds
one `x` node under several parents. `registerNullableGroupByKeys` builds
the key's "sub-keys already Nullable" shape from `key->clone()`, which
keeps that sharing, and `convertNestedGroupByKeysToNullable` converted the
shared `x` in place on its first visit. Later parents of the same node
then saw an already converted `x`, did not match it as a key, and were not
re-resolved, so the shape kept stale non-Nullable types and matched no
resolved expression. The projection, HAVING and ORDER BY then computed the
key again from the NULL of `x`, typed as the non-Nullable key: wrong rows
for ROLLUP / CUBE / GROUPING SETS, and with the OR chain kept a header
type mismatch that aborts a debug build in `count`.

Copy a node that several parents hold before changing it in place
(copy-on-write, the same idiom as LogicalExpressionOptimizerPass). Inside
the key clone a node's use count is the number of parent slots holding
it, so a node is now changed only while one parent owns it, and every
reference is converted exactly as in the tree that is built with the
cache off. A copy only "when seen again" is not enough: the first visit
has already changed the shared node by then.

Regression since 26.6 (ClickHouse#88043 cache, ClickHouse#107050 exact key shapes); 26.3 is
correct. Found while reviewing ClickHouse#125846.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`collectGroupByKeyNodes` hashed every candidate (a function node named
like a key) with a walk over its whole subtree, formatting each constant
again. A key that is a nested `and` chain makes every level a candidate,
so collection was quadratic in the chain length (times the size of the
constants), in both visitors, even when the pass rewrites nothing.
`getGroupByKeyHash` now combines the hashes of the children and stores
the hash of every node it visits, so each node is hashed once.

Measured on a debug build, `EXPLAIN QUERY TREE passes=40` vs `passes=41`
of `WITH range(10000) AS a SELECT count() FROM numbers(1) GROUP BY
and(has(a, number + N - 1), and(..., has(a, number)))`: 100 levels
0.48 -> 5.84 s before, 0.51 -> 0.58 s after; 200 levels 0.82 -> 21.79 s
before, 0.60 -> 0.60 s after; master shows no cost in the pass. The
2000/4000-key workloads of the earlier rounds are unchanged.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3da1448

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log infra (upgrade harness), not from this PR: the table of 04627_lwd_rebuild_normal_projection_no_where left by the previous release has PROJECTION p (SELECT count() GROUP BY 0) with 0 as a constant key; the upgraded server reads 0 as a position at startup and skips it (Positional argument number 0 is out of bounds). The same error failed this check on 3 other PRs since 2026-11-20 #128105 (mine, open)
Mergeable Check, PR praktika rollups of the row above (Failed: Upgrade check (amd_release)) #128105 (mine, open)

No other job failed on this head (CIDB: 1 FAIL row, the one above); the run was the full suite (Review Threads: all review threads resolved).

Session id: cron:our-pr-ci-monitor:20261123-000024

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). pr-bugfix Pull request with bugfix, not backported by default v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants