Skip to content

Do not drop the whole GROUP BY when unwrapping injective functions of constants - #114981

Merged
nihalzp merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-group-by-injective-function-of-constant
Aug 29, 2026
Merged

nihalzp merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-group-by-injective-function-of-constant

Conversation

@groeneai

@groeneai groeneai commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #104863 (same logical error, closed earlier without this cause identified)

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 wrong results for a GROUP BY whose only key is an injective function of constants, for example SELECT 1 FROM t GROUP BY materialize(NULL). Such a key was removed by optimize_injective_functions_in_group_by, which left the query with no GROUP BY and no aggregation at all, so it returned one row per input row instead of one row per group. Over a Merge table that mixes a local and a remote child the same cause also raised the logical error Chunk info was not set for chunk in GroupingAggregatedTransform.

Description

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: when such a key was
the only one and the query had no aggregate function, GROUP BY became empty and the query stopped
aggregating.

Under a Merge table mixing a child that aggregates with one that does not, the un-aggregated
child's raw chunks reach a merge transform that requires aggregate state; both wordings of the
message occur, GroupingAggregatedTransform and MergingAggregatedTransform, depending on
distributed_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
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 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), k still groups by k alone.

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 = 0 and a plain GROUP BY NULL key 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

  • Merged into: 26.9.1.316 (included in 26.9 and later)

groeneai and others added 2 commits August 15, 2026 22:35
… 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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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 was raised and executed. Findings and verdicts:

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
no-fasttest with a reason that was false. tests/config/install.sh links clusters.xml
unconditionally and ci/jobs/fast_test.py passes --shard, so Fast test does have the cluster;
meanwhile without a shard tag the test still ran under the one job group that passes
--no-shard, in a parallel-replicas configuration nothing here validated. Fixed: the tag line is
now -- Tags: shard. Measured both ways locally (--shard OK, --no-shard skipped), and the
same shape already in master, 03471_group_by_computed_key_merge_over_distributed, has 11092
Fast test OK runs in the last 30 days with exactly this tag line.

❌ The assertions could pass against unfixed code. The runner randomizes
optimize_injective_functions_in_group_by to false in about 5% of runs, and with the optimization
off the pre-fix code is already correct. Fixed by pinning it, along with group_by_use_nulls and
the two-level thresholds. The negative control is what makes this more than a claim: flipping the
pin back to 0 makes the abort disappear entirely on the unfixed binary, and flipping every pin
makes every value arm pass against unfixed code.

❌ The first Merge arm did not pin distributed_aggregation_memory_efficient, which is
randomized, so on a zero draw it became a duplicate of the next line and the memory-efficient path
was covered by neither. Fixed: the two arms now pin 1 and 0. On unfixed code they reproduce
different transforms, GroupingAggregatedTransform and MergingAggregatedTransform, which is why
one fix closes both wordings of the message.

💡 The new source comment restated the mechanism that the commit message already carries. Trimmed
to the invariant alone.

The .reference file is byte-unchanged across the round, so no assertion changed value; the round
only fixed which configurations the arms run in. Re-ran 50 randomized runs sequentially and 50 at
4-way parallelism after it: all pass, zero guard hits.

Round 1 - 1 not accepted

⚠️ Pinning prefer_localhost_replica = 0 was suggested, on the theory that choosing a local
replica avoids the mechanism. It does not. The repro runs with that setting at its default true
on a cluster whose both shards are the same local address and still aborts 3 times out of 3. The
mechanism needs heterogeneity, not remoteness: the local Merge child gets no Aggregating step
while the Distributed child's shards do. Pinning it would add no coverage and move the test off
the configuration in which the abort is actually demonstrated.

Round 2 - 1 noted, not blocking

💡 The new comment says the runner randomizes all five pinned settings. Three of them are
randomized; group_by_use_nulls does not appear in the runner's randomization table at all and
enable_analyzer is varied per job group. Those two are pinned because they are the pass's two
early-return fences. Not worth another round to reword, and the same form is already in master.

No blocker or major finding is open. The source logic was unchanged in the fix round, verified by
stripping comments and whitespace from both revisions and confirming they are identical.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, both faces. Wrong results: SELECT count() FROM (SELECT 1 FROM t1 GROUP BY materialize(NULL)) on a 10-row table returns 10 instead of 1, in clickhouse local, default settings. Logical error: SELECT multiIf(0, NULL, materialize(toNullable(NULL))) FROM merge('pr2', '^(t1|d1)$') GROUP BY ALL over a MergeTree plus a Distributed child, 3/3 on a real server. Neither is probabilistic.
b Root cause explained? 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 hasGroupBy() false, and the query stopped aggregating. Under a Merge table the un-aggregated child's raw chunks then reach a merge transform that requires aggregate state.
c Fix matches root cause? Yes. The pass that empties the key list is the pass that now refuses to assign an empty one. No widened bound, no no-random-* tag, no data-size reduction, no guard at the failure site, and no fabricated chunk metadata.
d Test intent preserved / new tests added? New test 04805_group_by_injective_function_of_constant. It fails on master (with the abort) and passes with the fix. Both existing fences in this pass, group_by_use_nulls and CUBE/ROLLUP/GROUPING SETS/TOTALS, are covered and unchanged, and the getChunkInfos().empty() guards are left intact.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (base dc4aa909d3d4b78c, fix f0e5c9cb3c938b6b), with buildId() asserted against the ELF on every server start. Wrong results 10 to 1. Logical error: base aborts 3/3 with 2 guard hits per run and a stack matching the CI carrier at MergingAggregatedMemoryEfficientTransform.cpp:282; fix passes 3/3 with 0 guard hits. Re-confirmed on the round-1 binary through the stateless runner: base dies mid-test with 2 guard hits, fix is [ OK ] with 0.
f Fix is general across code paths? The invariant has three sibling carriers. OptimizeLimitByInjectiveFunctionsPass and the non-analyzer TreeOptimizer::optimizeGroupBy already refuse an emptied key list; only the analyzer's GROUP BY pass did not, and that asymmetry was the bug. Both wordings of the message, GroupingAggregatedTransform and MergingAggregatedTransform, are fixed by this one change. The other injective-key passes cannot empty the list: OptimizeGroupByFunctionKeysPass keeps any key that is not a function of another key, and the remaining two only read the list.
g Fix generalizes across inputs (params/datatypes/wrappers)? Verified across materialize(NULL), materialize(1), materialize('a'), materialize('b'), the nested wrap toString(materialize(NULL)), the fuzzer's multiIf(...) expression, GROUP BY ALL over a constant-folded list, multi-key, empty and non-empty tables, with and without aggregate functions, both values of empty_result_for_aggregation_by_constant_keys_on_empty_set, group_by_use_nulls, distributed_aggregation_memory_efficient and enable_analyzer. The test also asserts via EXPLAIN QUERY TREE that the optimization still fires where it is valid, so the fix is not a silent performance regression: GROUP BY toString(k) still unwraps, and GROUP BY materialize(NULL), k still groups by k alone. Both values of distributed_aggregation_memory_efficient are pinned explicitly rather than left to the runner, and each reproduces a different transform on unfixed code, GroupingAggregatedTransform at 1 and MergingAggregatedTransform at 0.
h Backward compatible? (maintainer-approved exception only) No setting, default or serialization format changes, so no SettingsChangesHistory.cpp entry applies. Affected queries do change their row count, which is the fix. Each changed shape agrees with three independent references: optimize_injective_functions_in_group_by = 0, enable_analyzer = 0, and a plain GROUP BY NULL key that this pass never rewrites. The previous behaviour stays reachable with optimize_injective_functions_in_group_by = 0.
i Invariants and contracts preserved? The pass's contract is that it rewrites keys without changing results, and that now actually holds: across 25 shapes the patched default output is byte-identical to running with the optimization disabled, where before it diverged on 7. The shared helper's logic is unchanged, so LIMIT BY is unaffected by construction and its results are identical on both arms. Downstream, every chunk entering a merge-aggregated transform again carries chunk info. No lock, lifetime or durability surface is touched.

Randomized runs: 50/50 pass sequential and 50/50 pass at 4-way parallelism, 0 guard hits.

The test is tagged shard for its two-host cluster dependency, and every setting its assertions depend on is pinned in the test. Both were verified by negative control: without --shard the test skips rather than running in an unvalidated configuration, and with the pins removed the value arms pass against unfixed code, which is what the pins prevent.

Session id: cron:clickhouse-impl-slot-4:20260815-235200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @nihalzp, could you review this? unwrapInjectiveFunctionsInKeys skips constant arguments, so a GROUP BY key that is an injective function of a constant unwrapped to nothing and OptimizeGroupByInjectiveFunctionsPass assigned the empty list unconditionally, leaving the query with no GROUP BY and no aggregation, which returns one row per input row and, over a Merge table mixing an aggregating and a non-aggregating child, raises the logical error at MergingAggregatedMemoryEfficientTransform.cpp:282. The guard mirrors what the LIMIT BY pass and the non-analyzer path already do.

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b2d1f16]

Summary: ✅


AI Review

Summary

This PR fixes the main wrong-result case where a lone GROUP BY materialize(const) was optimized away completely, but the current approach still breaks the constant-key empty-set contract under empty_result_for_aggregation_by_constant_keys_on_empty_set = 0. I do not consider it merge-ready until that compatibility path is preserved as well.

Findings

❌ Blockers

  • [src/Analyzer/Passes/OptimizeGroupByInjectiveFunctionsPass.cpp:60-64, src/Planner/PlannerExpressionAnalysis.cpp:236-239, src/Planner/Planner.cpp:676-678] [dismissed by author -- https://github.com/Do not drop the whole GROUP BY when unwrapping injective functions of constants #114981#discussion_r3864565590] Preserving the original materialize(NULL) key fixes the non-empty-table wrong result, but it also stops the analyzer from classifying the key as constant. PlannerExpressionAnalysis only sets group_by_with_constant_keys for actual ConstantNodes, and Planner.cpp only consults empty_result_for_aggregation_by_constant_keys_on_empty_set when both that bit is set and aggregation_keys is empty. As a result, SELECT count() FROM (SELECT count() FROM empty_t GROUP BY materialize(NULL) SETTINGS empty_result_for_aggregation_by_constant_keys_on_empty_set = 0) still returns zero rows even though GROUP BY NULL and enable_analyzer = 0 return one row.
    Suggested fix: preserve the "all remaining GROUP BY keys are constant-valued" invariant when unwrapInjectiveFunctionsInKeys would otherwise erase the whole list, or rewrite the lone constant-derived key into a real ConstantNode without reintroducing the dictGet/name-clash regressions discussed in the thread; then add a focused empty-table regression for the non-default setting.
Tests
  • ⚠️ [tests/queries/0_stateless/04805_group_by_injective_function_of_constant.sql:28-30] The new regression suite covers the default empty-table behavior, but it never exercises empty_result_for_aggregation_by_constant_keys_on_empty_set = 0, which is exactly where the remaining divergence from GROUP BY NULL lives. Add that one-row-vs-zero-row check once the planner fix is in place.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit b2d1f16.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 16, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b2d1f161f with master 617af45cc (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
Binary Master PR Δ
programs/clickhouse-stripped 710.07 MiB 707.02 MiB -3.06 MiB (-0.43%)

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 units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 85a7776

CI is fully finished on this head: 177 check-runs, none queued or in progress, Config Workflow
and Finish Workflow both green, result_pr.json reports 0 DROPPED leaves (158 OK / 18 SKIPPED),
so the run had genuine coverage.

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
Stress test (amd_tsan) / Logical error: Join is supported only for pipelines with one output port, got 2 and 1 (STID 4488-4e11) pre-existing trunk logical error in joinPipelinesYShaped, not caused by this PR (25 distinct PRs / 26 builds in 14d) #109393 (mine, open)
Config Workflow / Pre Hooks, Finish Workflow / Post Hooks (rows at 00:58:16Z, 00:59:58Z, 01:09:11Z, 01:11:37Z) superseded, not open failures: both jobs re-ran green on this same commit (Config Workflow 01:29:36Z, Finish Workflow 07:13:23Z) no owner needed, the later successful run on this head replaces them

Not PR-caused: this PR changes GROUP BY unwrapping of injective functions of constants; the
failing assertion is in the full_sorting_merge JOIN pipeline builder, and the same STID fires
across 25 unrelated PRs in the last 14 days.

Session id: cron:our-pr-ci-monitor:20260816-083000

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@nihalzp nihalzp self-assigned this Aug 26, 2026
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())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: 1 becomes nodes: 3). A fix has to substitute per key and never retain a function's constant parameters.
  • 04628_split_filter_name_clash_header_leak: split_fired goes from 1 to 0. That one is not specific to my patch. On this PR's own head the same query gives split_fired = 1 for GROUP BY materialize(7), but 0 for GROUP BY 7 and 0 for GROUP 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d31a54e

Every failure below has an owner: a fixing PR (ours 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
Docs examples / Function/catboostEvaluate#0 trunk defect, not from this PR: the docs-examples known-failures list still carries an entry for an example that no longer exists, so the job fails with "1 known failure(s) no longer exist and must be removed" #116566 (external, merged 2026-08-26T20:09:12Z). This run predates the fix, so merging master clears it.

Two independent measurements put the fix outside the tested tree: this run was dispatched at
2026-08-26T15:40:11Z, before #116566 merged, and the job's own output reports 2207 examples of 1603 entities (2088 ok, 119 not ok), which is the count without catboostEvaluate restored (it becomes 2208 of
1604 with the fix present). No other check failed on this head.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to pick up the revert in #116566, which restores src/Functions/catboostEvaluate.cpp and makes the Function/catboostEvaluate#0 pin in tests/docs_examples/known_failures.txt valid again.

Docs examples was the only red on the previous head, and it fails the Mergeable Check aggregator, so picking that revert up is what lets this PR go green. The failing run started 4.5 hours before the revert landed, and its log reports Running 2207 examples of 1603 entities, the count with catboostEvaluate absent, so the fix was never in the tested tree.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fdf2ffd

Every failure below has an owner: a fixing PR (ours 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
AST fuzzer (amd_debug, targeted) / Invalid status NotActive for associated output (STID 3336-35d1) pipeline port-status invariant violated inside StrictResizeProcessor::prepare; the abort is in the executor, not in query analysis #116478 (external, open)

Attribution from the stack, not from the message text: the aborting frame is
src/Processors/ResizeProcessor.cpp:216 in StrictResizeProcessor::prepare, reached via
ExecutingGraph::updateNode and PipelineExecutor::executeStepImpl. #116478 fixes that exact
assertion in that exact processor. The only other occurrence of this signature in 30 days is on
#99495, which predates this branch by 6 days, and there are no master rows.

One thing worth stating explicitly rather than leaving implicit: the fuzzed query does reach this PR's
code path, since GROUP BY GROUPING SETS ((toString(_CAST('0', 'Time64(7)')))) is an injective function
of a constant. This PR changes which keys survive GROUP BY, which can change the pipeline shape and so
change whether the resize processor is exercised. It does not change resize or parallelism itself, and the
violated invariant is entirely inside the executor, so the defect is the one #116478 addresses rather than
one introduced here. If that PR merges and this signature still fires on a head containing it, the link
will be revisited instead of re-cited.

No other check failed on this head.

Session id: cron:our-pr-ci-monitor:20260827-113000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b2d1f16

CI is fully finished on this head: 170 check-runs, none queued or in progress, a single PR
workflow run (33191833022), Config Workflow and Finish Workflow both green, Mergeable Check
green, and result_pr.json reports 0 DROPPED leaves, so the run had genuine coverage.

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
Stress test (amd_asan_ubsan) / Logical error: Not-ready Set is passed as the second argument for function 'globalNotIn' (STID 0250-41a5) chronic trunk set-readiness defect: an in-place subquery set is left unbuilt and FunctionIn then aborts on the null get(). CIDB 30 days for this STID: 230 hits across 177 distinct PRs and 24 distinct master commits, continuous since 2026-07-30 15:13Z, most recently 2026-08-29 01:31Z. #102308 (external, open)

Not from this PR: the diff only stops the whole GROUP BY being dropped when an injective function
of a constant is unwrapped, and never reaches PreparedSets or the IN/GLOBAL IN set-building
path. The tracking issue for the family is #107619.

Session id: cron:our-pr-ci-monitor:20260829-043000

@nihalzp
nihalzp added this pull request to the merge queue Aug 29, 2026
Merged via the queue into ClickHouse:master with commit ab9ebb0 Aug 29, 2026
344 of 345 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
@groeneai

groeneai commented Aug 30, 2026 •

Copy link
Copy Markdown
Collaborator Author

Following up on discussion_r3864565590 and my two replies: I finished the investigation. It ends on one compatibility question that I should not answer on my own, and nothing is pushed.

Defect. Empty MergeTree, empty_result_for_aggregation_by_constant_keys_on_empty_set = 0:
SELECT count() FROM (SELECT count() FROM empty_t GROUP BY materialize(NULL)) returns 0, where GROUP BY NULL and enable_analyzer = 0 return 1. The constant-key detector in analyzeAggregation is a node-type test on ConstantNode, so a key that is an injective function of constants never reaches the setting. Same for materialize(1) and toString(materialize(1)).

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. queryNodeToSelectQuery leaves use_source_expression_for_constants false (Utils.cpp:182), so a folded constant is serialized as _CAST(<literal>, '<type>') (ConstantNode.cpp:288) and a downstream site re-attaches that _CAST as the new source expression. Downstream therefore carries strictly less information than upstream, and any refusal that reads a constant's source expression can only fire upstream. Four attempts to name the topology instead, each falsified by measurement on a different site, all within one version:

  • is_distributed alone: a parallel-replicas initiator reads a plain MergeTree and is not distributed, while every replica is a secondary query.
  • + allow_experimental_parallel_reading_from_replicas: ParallelReplicasLocalPlan.cpp:216 zeroes that setting before the local replica replans in the same process, so the initiator keeps the key and the local plan drops it. Code: 8 at :316, at the default parallel_replicas_local_plan = 1.
  • + SelectQueryOptions::is_local_plan_for_distributed_query: closes that throw, but SelectQueryOptions::subquery resets the flag, so a nested subquery inside the local replan classifies again.
  • ClientInfo::collaborate_with_initiator: set only where a read-task extension exists, so custom-key parallel replicas has the same hole.

The one gate that does hold within a version is is_secondary_query. It is the only predicate here that cannot be false upstream and true downstream: when the initiator folds a constant, the literal is substituted into the query every downstream site reads, so all sites agree and no check is needed; when the text still carries an unfolded call, the initiator could not fold it and kept the key, and only a shard that folds it locally has to be told to keep it, which is what the existing server-constant refusal does. I built exactly that, pinned it from both sides, and then reverted it for one reason: it leaves a rolling upgrade of a sharded cluster failing with NOT_FOUND_COLUMN_IN_BLOCK, because a new shard removes a key an old coordinator kept.

Both of your 2026-02-08 commits on this predicate, cd1cff4e617a975 and 1d84244936c6f4f, changed which constants get removed with no protocol guard, so I cannot tell from the tree whether that window is a blocker here or the accepted cost.

@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: filesystemAvailable, addressToLine, addressToSymbol, getClientHTTPHeader and __getScalar report isServerConstant but, unlike the serverConstants.cpp family, do not override isSuitableForConstantFolding, so they fold on a distributed initiator where IFunction.h:291 says they must not. That is why a bare GROUP BY filesystemAvailable() over a Distributed table already fails with Code: 8 THERE_IS_NO_COLUMN today at default settings. #107775 is open on the filesystem part.

rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Sep 14, 2026
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]>
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants