Repository navigation
Conversation
… constants unwrapInjectiveFunctionsInKeys unwraps an injective function to its arguments and skips constant arguments, so a key that is an injective function of a constant unwraps to nothing and is dropped. OptimizeGroupByInjectiveFunctionsPass assigned that result unconditionally, so when such a key was the only one and the query had no aggregate function, GROUP BY became empty and the query stopped aggregating. Two visible faces. On a single local table with default settings, SELECT count() FROM (SELECT 1 FROM t GROUP BY materialize(NULL)) returned one row per input row instead of one row per group. Under a Merge table that mixes a child which aggregates with one that does not, the un-aggregated child's raw chunks reach a merge transform that requires aggregate state, raising the logical error "Chunk info was not set for chunk in GroupingAggregatedTransform" (or the MergingAggregatedTransform wording, depending on distributed_aggregation_memory_efficient). Assign the unwrapped key list only when it is non-empty. That is what OptimizeLimitByInjectiveFunctionsPass already does for LIMIT BY and what the non-analyzer TreeOptimizer::optimizeGroupBy does via appendUnusedGroupByColumn; of those three sibling paths only the analyzer's GROUP BY pass lacked the guard. The shared helper is unchanged, so LIMIT BY is unaffected. A per-key variant that keeps only the constant-derived key was not used: it would weaken the optimization when another key survives, and it is the branch added in 462445c and removed the next day in 355909e. With the whole-list guard, GROUP BY materialize(NULL), k still groups by k alone. Across 25 shapes the patched default now produces output identical to running with optimize_injective_functions_in_group_by = 0, where before it diverged on seven of them; enable_analyzer = 0 and a plain GROUP BY NULL key agree on the new values. The previous behaviour remains reachable with that setting. Co-Authored-By: Claude Fable 5 <[email protected]>
… new test Review round 1 on the test file only; the fix itself is unchanged apart from shortening one comment. The test builds a Distributed over test_cluster_two_shards, whose second shard is host 127.0.0.2, so it needs the shard tag. It carried no-fasttest instead, with a reason that was wrong: Fast test does have the cluster (tests/config/install.sh links clusters.xml unconditionally and ci/jobs/fast_test.py passes --shard), and without the shard tag the test still ran under the one job group that passes --no-shard, ParallelReplicas, in a parallel-replicas configuration that nothing here validated. Tagging it shard both declares the dependency and skips it there. Pin the settings the assertions depend on. The runner randomizes optimize_injective_functions_in_group_by to false about 5% of runs, and with the optimization disabled the unfixed code is already correct, so those runs would pass against unfixed code; group_by_use_nulls is the same kind of fence. The two-level thresholds decide whether the memory-efficient path is reached at all. Also pin distributed_aggregation_memory_efficient explicitly on the first Merge arm: it was randomized, so on a zero draw that line became a duplicate of the next one and neither covered the memory-efficient path. The two arms now cover both values deterministically, and on unfixed code each reproduces a different transform, GroupingAggregatedTransform at one and MergingAggregatedTransform at zero. The reference file is unchanged, so no assertion changed value; the round only fixes which configurations the arms run in. The per-query overrides for group_by_use_nulls and enable_analyzer are kept, since query-level SETTINGS beat the session value and those arms exist to exercise the fences and the legacy path. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (2 rounds, 6 findings adjudicated)Before publishing I reviewed this change cold and ran it past an independent model twice. One fix Round 1 - 4 accepted, all in the test file, all test-liveness ❌ The test declared a two-host cluster dependency in code but not in tags, and carried ❌ The assertions could pass against unfixed code. The runner randomizes ❌ The first 💡 The new source comment restated the mechanism that the commit message already carries. Trimmed The Round 1 - 1 not accepted
Round 2 - 1 noted, not blocking 💡 The new comment says the runner randomizes all five pinned settings. Three of them are No blocker or major finding is open. The source logic was unchanged in the fix round, verified by |
Pre-PR validation gate (click to expand)
Randomized runs: 50/50 pass sequential and 50/50 pass at 4-way parallelism, 0 guard hits. The test is tagged Session id: cron:clickhouse-impl-slot-4:20260815-235200 |
|
cc @vdimir @nihalzp, could you review this? |
|
Workflow [PR], commit [b2d1f16] Summary: ✅
AI ReviewSummaryThis PR fixes the main wrong-result case where a lone Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit b2d1f16.
Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units7 translation units recompiled, 7 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 85a7776CI is fully finished on this head: 177 check-runs, none queued or in progress, Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Not PR-caused: this PR changes Session id: cron:our-pr-ci-monitor:20260816-083000 |
| auto new_group_by = unwrapInjectiveFunctionsInKeys(group_by, allow_suspicious_types); | ||
|
|
||
| /// At least one key is needed for GROUP BY: with an empty key list the query does not aggregate. | ||
| if (!new_group_by.empty()) |
There was a problem hiding this comment.
This still misses one GROUP BY const semantic: empty-input behavior under empty_result_for_aggregation_by_constant_keys_on_empty_set = 0.
materialize is deliberately not suitable for constant folding (FunctionMaterialize::isSuitableForConstantFolding() == false), so when this branch keeps the original key, the analyzer later reaches PlannerExpressionAnalysis with a non-empty, non-ConstantNode key list. That code only sets group_by_with_constant_keys for actual ConstantNodes, so the compatibility path that makes GROUP BY NULL return one row on an empty table never fires here.
A focused repro is:
SELECT count() FROM
(
SELECT count()
FROM empty_t
GROUP BY materialize(NULL)
SETTINGS empty_result_for_aggregation_by_constant_keys_on_empty_set = 0
);GROUP BY NULL and enable_analyzer = 0 return one row here, but this path still behaves like grouping by an ordinary key and returns zero rows. Could we preserve the “all grouping keys are constant-valued” bit instead of only keeping the original function node, and add a regression for the non-default setting?
There was a problem hiding this comment.
Confirmed, and it is a regression this PR introduces. Measured with two debug binaries differing only by this PR's diff (base 914e1208, PR head 5c2a1ec8), empty table, count() aggregate, empty_result_for_aggregation_by_constant_keys_on_empty_set = 0:
GROUP BY key |
base | this PR | enable_analyzer = 0 |
|---|---|---|---|
materialize(NULL) |
1 | 0 | 1 |
materialize(1) |
1 | 0 | 1 |
toString(materialize(1)) |
1 | 0 | 1 |
NULL |
1 | 1 | 1 |
So the class is wider than the single repro, and base agreed with the old analyzer before this PR. toString(1) returns 1 in every arm, which is the control showing the compatibility path itself is reachable in this fixture. At the default value the PR is unaffected (0, matching enable_analyzer = 0), so the correction it makes there still holds.
Your mechanism is right. I tried the direct fix, which is to stop dropping constant arguments in unwrapInjectiveFunctionsInKeys so the key unwraps to a real ConstantNode and the existing constant-key handling applies. It closes all three rows, and keeps both the LOGICAL_ERROR fix and every non-empty-table result, but it breaks two existing tests, so I am not pushing it:
01376_GROUP_BY_injective_elimination_dictGet:dictGet(name, attr, number)then keeps the two parameter constants as grouping keys (nodes: 1becomesnodes: 3). A fix has to substitute per key and never retain a function's constant parameters.04628_split_filter_name_clash_header_leak:split_firedgoes from 1 to 0. That one is not specific to my patch. On this PR's own head the same query givessplit_fired= 1 forGROUP BY materialize(7), but 0 forGROUP BY 7and 0 forGROUP BY NULL. Reaching the compatibility path requires the key to be treated as a removable constant, and that also inherits the constant-key plan shape.
Preserving the bit is therefore a trade-off between two existing behaviours rather than a local change, and I would rather settle it deliberately. The regression arms you asked for are written and reproduce the table above.
There was a problem hiding this comment.
Correction to my previous reply. I called this a regression introduced here; the measurement below shows the setting is already inert for this key class on master, so this branch is not what stops the compatibility path from firing.
Same two binaries, empty table, count() aggregate, value is the returned row count:
GROUP BY key, setting value |
base | this PR | enable_analyzer = 0 |
|---|---|---|---|
NULL, 1 (default) |
0 | 0 | 0 |
NULL, 0 |
1 | 1 | 1 |
materialize(NULL), 1 (default) |
1 | 0 | 0 |
materialize(NULL), 0 |
1 | 0 | 1 |
GROUP BY NULL moves with the setting on both binaries, so the compatibility path is reachable in this fixture and the fixture is not blind. materialize(NULL) moves on neither. On base its 1 is the dropped GROUP BY degenerating into a plain aggregate, not the compatibility path, which is why base returns 1 at the default value too, where the correct answer is 0. So the path was not firing before this change either; what this change does is replace the inert path's value, wrong at the default, with one that is right at the default. At empty_result_for_aggregation_by_constant_keys_on_empty_set = 0 the value does move from 1 to 0, so the residual you point at is real and user visible.
It is also not a general planner gap. Six constant-valued keys whose outer function is not injective, so the pass leaves them untouched, return 0 at that setting on base, on this PR and on enable_analyzer = 0 alike: length(materialize('ab')), if(materialize(1), 2, 3), materialize(1) = 1, sipHash64(materialize(1)), materialize(1) % 3, abs(materialize(-1)). Each of them still groups on base, one row over a ten row table, so they really are keys the pass never rewrites. Both engines scope the compatibility path to keys that reduce to a literal.
Preserving the bit means having the key counted as a removable constant, and that is the one thing an existing test cannot have. On this head the values arm of 04628_split_filter_name_clash_header_leak measures split_fired = 1 for GROUP BY materialize(7) and 0 for GROUP BY 7; its clash needs a key literally named materialize(7). Keeping materialize(const) as a real grouping key and counting it as a constant key are contradictory, so closing this needs a plan shape decision plus a repair to a regression test that is not mine.
I am therefore not widening this PR. It corrects the default-value cell above, plus the non-empty table result that this PR is about (SELECT 1 FROM t GROUP BY materialize(NULL) over ten rows: base 10, this PR 1, enable_analyzer = 0 1). I am tracking the non-default value as its own item with these measurements and will link the fix here.
CI finish ledger - d31a54eEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Two independent measurements put the fix outside the tested tree: this run was dispatched at Session id: cron:our-pr-ci-monitor:20260827-043000 |
Picks up the revert in ClickHouse#116566, which restores catboostEvaluate and makes the Function/catboostEvaluate#0 pin in tests/docs_examples/known_failures.txt valid again. That check was the only red on this branch and it fails the Mergeable Check aggregator. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Merged master to pick up the revert in #116566, which restores
Nothing changed in the code under review: the diff against master is the same 4 files at +97/-2, with a patch-id identical to the approved head. The regression test passes on the merged tree. |
CI finish ledger - fdf2ffdEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Attribution from the stack, not from the message text: the aborting frame is One thing worth stating explicitly rather than leaving implicit: the fuzzed query does reach this PR's No other check failed on this head. Session id: cron:our-pr-ci-monitor:20260827-113000 |
CI finish ledger - b2d1f16CI is fully finished on this head: 170 check-runs, none queued or in progress, a single Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Not from this PR: the diff only stops the whole Session id: cron:our-pr-ci-monitor:20260829-043000 |
ab9ebb0
|
Following up on Defect. Empty Why the fix cannot be confined to queries with a single planning site. One key list is classified at up to four sites, and they do not see the same tree.
The one gate that does hold within a version is Both of your 2026-02-08 commits on this predicate, @alexey-milovidov so, one question: is the rolling-upgrade window acceptable on this predicate, or should this divergence stay documented behaviour instead? I will not push anything until you answer. Separately, and not something I am proposing to touch: |
allow_window_partitions_independently arrived after this branch was written, in ClickHouse#114783 (ec46c0e), so the window consumer of isPartitionKeyFunctionOfKeys had no arm of its own. It has one now, in the test file that already covers the aggregation, DISTINCT, LIMIT BY, set-building and sharding-key consumers. The carrier is Date + INTERVAL 1 MONTH rather than the float shape issue ClickHouse#116268 reports, because a floating point partition key is rejected outright (Code: 36), so a float carrier has to reach its partition through an integer valued indirection such as toInt64(x * 1e21), and that shape never satisfies isPartitionKeyFunctionOfKeys. Measured on a pre-fix build, every line of the float window arm is identical with and without this change, including a bare column control, so it would have asserted nothing. A Date is a legal partition key and needs no indirection. The float half of that issue is a GROUP BY, does reproduce, and is covered by the existing t_float arms. Measured on a pre-fix build of master, the forced arm and the arm that sets nothing at all both return three distinct window counts where one is correct, and both plan tokens the optimization prints read 1; with this change all three value arms return a single count and both tokens read 0. The arm that sets no setting matters most: the cost heuristic accepts these 39 partitions at the max_threads the file already pins, so the wrong answer needs no opt in. The integer control next to it is unchanged in every arm, which is what attributes the section to the operand type rather than to the fixture or the window shape. Both plan tokens are asserted because the change has to decline at both decision sites, the per-partition read request and the scatter skip above it. The reference line for the empty key arm is no longer red. It asserted the value that needs the guard from ClickHouse#114981, which merged as ab9ebb0 and arrives here through a master merge, so the whole file now passes as committed, 50 runs out of 50, with no reference edited. For the record, the precedent for deleting a name based injectivity list in this helper is 9aa0341 (Nikolai Kochetov), which did exactly this for materialize. Co-Authored-By: Claude Opus 5 <[email protected]>
Related: #104863 (same logical error, closed earlier without this cause identified)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results for a
GROUP BYwhose only key is an injective function of constants, for exampleSELECT 1 FROM t GROUP BY materialize(NULL). Such a key was removed byoptimize_injective_functions_in_group_by, which left the query with noGROUP BYand no aggregation at all, so it returned one row per input row instead of one row per group. Over aMergetable that mixes a local and a remote child the same cause also raised the logical errorChunk info was not set for chunk in GroupingAggregatedTransform.Description
unwrapInjectiveFunctionsInKeysunwraps an injective function to its arguments and skips constantarguments, so a key that is an injective function of a constant unwraps to nothing and is dropped.
OptimizeGroupByInjectiveFunctionsPassassigned that result unconditionally: when such a key wasthe only one and the query had no aggregate function,
GROUP BYbecame empty and the query stoppedaggregating.
Under a
Mergetable mixing a child that aggregates with one that does not, the un-aggregatedchild's raw chunks reach a merge transform that requires aggregate state; both wordings of the
message occur,
GroupingAggregatedTransformandMergingAggregatedTransform, depending ondistributed_aggregation_memory_efficient, and one fix closes both. Found by the fuzzers, e.g.AST fuzzer (amd_debug).
The fix assigns the unwrapped list only when it is non-empty, which is what
OptimizeLimitByInjectiveFunctionsPassalready does forLIMIT BYand what the non-analyzerTreeOptimizer::optimizeGroupBydoes viaappendUnusedGroupByColumn. Of those three sibling pathsonly the analyzer's
GROUP BYpass lacked the guard. The shared helper is unchanged, soLIMIT BYis unaffected. A per-key variant was deliberately not used: it would weaken the optimization when
another key survives, and it is the branch added in 462445c and removed the next day in
355909e.
GROUP BY materialize(NULL), kstill groups bykalone.Affected queries now return a different row count, which is the point of the fix. Across 25 shapes
the patched default is byte-identical to running with
optimize_injective_functions_in_group_by = 0,where before it diverged on 7 of them;
enable_analyzer = 0and a plainGROUP BY NULLkey agree.The old behaviour stays reachable with that setting. The new test fails on master and passes here.
Workflow [PR]
Sync PR [sync-upstream/pr/114981]
Version info
26.9.1.316(included in26.9and later)