Repository navigation
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
Conversation
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]>
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).
Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20261014-182100 |
|
Workflow [PR], commit [3da1448] Summary: ❌
AI ReviewSummaryThe PR preserves Final VerdictStatus: ✅ Approve |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20261014-155600 |
|
cc @KochetovNicolai @yakov-olkhovskiy, could you review this and add |
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]>
CI finish ledger - a9b85d3Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261016-020005 |
|
Fixing PR for 05332_autopr_min_bytes_per_replica_events created: #126189 |
…-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]>
Build profile diff (arm_release)Commit 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]>
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]>
CI finish ledger - 65d5224Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261030-183004 |
|
@groeneai pull master and fix CI |
…-logical-chain-rewrites Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
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 |
…-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]>
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
|
Merged
About the red |
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]>
|
@groeneai master is merged ( |
|
I can't resolve that thread: it was opened by |
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]>
CI finish ledger - 3da1448Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
No other job failed on this head (CIDB: 1 Session id: cron:our-pr-ci-monitor:20261123-000024 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
NOT_FOUND_COLUMN_IN_BLOCKand wrong results when a comparison that is aGROUP BYkey is also an operand of anORorANDchain, for exampleSELECT (x = 1) OR (x = 2) OR (x = 3), count() FROM t GROUP BY x = 1, x = 2, x = 3. WithGROUP BY ROLLUP(x, x = 1)such a chain returned a wrong value on the rows wherex = 1is 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 = 3throwsNOT_FOUND_COLUMN_IN_BLOCK, and withGROUP BY ROLLUP(x, x = 1)such anORreturns a wrong value wherex = 1is rolled up.After
GROUP BYan expression equal to a key is read from the aggregation result.LogicalExpressionOptimizerPassrewrote a key operand like any comparison: merged intoIN/NOT IN, folded, used to derive conjuncts, or flattened into the enclosingand. The result then needsx, gone after aggregation (or, in aROLLUP, rolled up differently).Before rewriting a query level, the pass now records its comparison and
andnodes that equal aGROUP BYkey (undergroup_by_use_nullsignoring types, as a copy afterGROUP BYcan beNullableat 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 withenable_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 TREEwith 51 keys and a 2000-operandOR: 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_nullstests pass (the others fail without it too).05394now expects no derivation into a bareandkey.LIKEchains (ConvertOrLikeChainPass): #125894.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/125846]