Skip to content

Fix optimize_injective_functions_in_group_by changing results with GROUPING SETS and WITH TOTALS - #110721

Merged
alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-injective-functions-group-by-modifiers
Jul 31, 2026
Merged

alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-injective-functions-group-by-modifiers

Conversation

@groeneai

@groeneai groeneai commented Jul 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #110715

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed optimize_injective_functions_in_group_by changing query results for GROUP BY GROUPING SETS and GROUP BY ... WITH TOTALS. The setting is documented as result-preserving, but eliminating an injective function of a grouping key produced a wrong value (or dropped a row) for rows where that key is absent from the aggregated set (a GROUPING SETS non-member set) or for the WITH TOTALS row. The wrong value could coincide with a genuine key value, making a super-aggregate row indistinguishable from a real group in the same result set.

Description

OptimizeGroupByInjectiveFunctionsPass rewrites an injective f(g) in the GROUP BY key list to g and recomputes f(g) in the output projection. That is only valid when every output row still carries g. It does not hold when a GROUP BY modifier emits rows where the key is absent from the aggregated set: such a row outputs the key column default, so the projection computes f(defaultOf(g)) instead of defaultOf(typeOf(f(g))).

The pass already bails on CUBE/ROLLUP and group_by_use_nulls for the same reason. This extends the guard to GROUPING SETS (non-member set rows) and WITH TOTALS (the totals row).

Reproducers from the issue, now returning identical output with the setting on and off:

SELECT materialize(3) AS x
FROM numbers(10)
GROUP BY GROUPING SETS (('str'), (materialize(3)))
ORDER BY x;
-- rows 0 and 3 (previously only 3 with the setting on)

SELECT toString(number) AS v, count()
FROM numbers(3)
GROUP BY v WITH TOTALS;
-- totals row v = '' (previously '0' with the setting on)

A reported consequence of the same defect: the value the projection computes for an absent key can collide with a genuine key value, so the two row classes stop being distinguishable rather than merely rendering differently.

SELECT k, toString(v), count()
FROM (SELECT number % 3 AS k, number AS v FROM numbers(10))
GROUP BY GROUPING SETS ((k), (k, toString(v)))
ORDER BY ALL;
-- super-aggregate row `0 '' 4`, distinct from the genuine group `0 '0' 1`
-- (previously `0 '0' 4` next to `0 '0' 1` with the setting on)

The optimization still applies to plain GROUP BY.

…ITH TOTALS

OptimizeGroupByInjectiveFunctionsPass rewrites an injective f(g) to g in the
GROUP BY key list and recomputes f(g) in the output projection. This relies on
every output row still carrying g, which does not hold when a grouping modifier
emits rows where the key is absent from the aggregated set: those rows output
the key column default. For such a row the projection then computes
f(defaultOf(g)) instead of defaultOf(typeOf(f(g))), changing the result even
though optimize_injective_functions_in_group_by is documented as
result-preserving.

The pass already bails on CUBE/ROLLUP and group_by_use_nulls for the same
reason. Extend that to GROUPING SETS (non-member set rows) and WITH TOTALS
(the totals row).

Closes: ClickHouse#110715

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Both issue reproducers fail on demand, single-threaded, enable_analyzer=1. SELECT materialize(3) AS x FROM numbers(10) GROUP BY GROUPING SETS (('str'),(materialize(3))) ORDER BY x returns only 3 with the setting on vs 0,3 with it off; SELECT toString(number) AS v, count() FROM numbers(3) GROUP BY v WITH TOTALS totals row is 0 on vs empty off.
b Root cause explained? The pass rewrites injective f(g) in the GROUP BY key list to g and recomputes f(g) in the output projection, assuming every output row still carries g. A GROUPING SETS non-member row and the WITH TOTALS row output the key column default instead, so the projection computes f(defaultOf(g)) (e.g. toString(0)='0') rather than defaultOf(typeOf(f(g))) (''), and a group-set row's key changes so it collapses/reorders.
c Fix matches root cause? Yes. It skips the rewrite for exactly the modifiers that emit a key-absent row, matching the existing bail for CUBE/ROLLUP and group_by_use_nulls which share the same property.
d Test intent preserved / new tests added? New test 04546_injective_functions_in_group_by_modifiers asserts identical output with the setting 0 and 1 for GROUPING SETS, WITH TOTALS, and plain GROUP BY.
e Both directions demonstrated? Yes. Without the fix =1 diverges from =0; with the fix =1 matches =0 for both reproducers; verified against the old analyzer (enable_analyzer=0) as the reference.
f Fix is general across code paths? Yes. The single pass is the only site of this rewrite; the guard now covers all four key-absent modifiers (CUBE, ROLLUP, GROUPING SETS, WITH TOTALS). No sibling code path performs the same rewrite.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The guard is purely structural (which GROUP BY modifier is present), independent of the injective function or its argument types, so it holds for any f/type/wrapper. The plain GROUP BY optimization is unchanged for all inputs.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default, format, or validation change. The setting stays documented as result-preserving; results now match the =0 (correct) output.
i Invariants and contracts preserved? Yes. Upholds the pass invariant stated in its own header ("a key is dropped or rewritten only when the result, including the columns GROUP BY outputs, does not change") — the fix restores that invariant for the modifier rows where it was violated.

Session id: cron:clickhouse-worker-slot-3:20260716-160700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd — could you review this? OptimizeGroupByInjectiveFunctionsPass rewrites injective f(g) to g in the GROUP BY keys and recomputes f(g) in the output; this is wrong for rows where the key is absent from the aggregated set (GROUPING SETS non-member sets, the WITH TOTALS row), which output the key default. The pass already bails on CUBE/ROLLUP and group_by_use_nulls for the same reason; this extends the guard to GROUPING SETS and WITH TOTALS.

@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [082731b]

Summary: ✅


AI Review

Summary

This PR closes the result-changing GROUP BY key rewrites for GROUPING SETS and WITH TOTALS on both the analyzer and legacy paths, and it adds focused regressions for the affected optimizations plus the legacy single-set GROUPING SETS exception. After rechecking the current head against the full diff and prior discussion, I do not see any remaining correctness or coverage gaps introduced by this patch; the one still-open discussion is about pre-existing analyzer behavior outside the modified code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 16, 2026
The WITH TOTALS EXPLAIN QUERY TREE in 02969 asserted the (incorrect)
unwrapping of the injective function in the totals row. With the pass now
skipping WITH TOTALS, the totals-key column is no longer unwrapped and the
totals-row value is the String default ('') instead of toString(0)='0'.
Plain GROUP BY and GROUP BY ALL sections are unchanged (optimization still
fires there).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
OptimizeGroupByFunctionKeysPass drops a GROUP BY key that is a function of
other keys and lets the output projection recompute it. Like the sibling
OptimizeGroupByInjectiveFunctionsPass, this is only valid when every output
row still carries those other keys. For WITH TOTALS and GROUPING SETS the
non-member/totals rows output the keys as their column defaults, so the
dropped key gets recomputed from those defaults (e.g. toString(number) from
number = 0 yields '0' instead of the String default ''), changing results.

Extend the CUBE/ROLLUP guard to GROUPING SETS and WITH TOTALS, mirroring the
injective-functions pass. Add regression cases for optimize_group_by_function_keys
to 04546. See ClickHouse#110715.

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

Copy link
Copy Markdown
Collaborator Author

Good catch. Fixed in 14c68bc.

`OptimizeGroupByFunctionKeysPass` relied on the same "every output row still carries the key" contract and only guarded CUBE/ROLLUP. Extended its early-return guard to `isGroupByWithGroupingSets()` and `isGroupByWithTotals()`, mirroring the injective-functions pass. Confirmed your reproducer on the pre-fix binary returns `v = '0'` in the totals row and `v = ''` after the guard. Added regression cases (WITH TOTALS + GROUPING SETS, plus a plain-GROUP BY case proving the optimization still applies) for `optimize_group_by_function_keys` to `04546_injective_functions_in_group_by_modifiers`.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT toString(number) AS v, number, count() FROM numbers(3) GROUP BY v, number WITH TOTALS ORDER BY number SETTINGS optimize_group_by_function_keys = 1 deterministically returns v = '0' in the totals row on the pre-fix binary.
b Root cause explained? OptimizeGroupByFunctionKeysPass drops a key that is a function of other keys and lets the output projection recompute it. Under WITH TOTALS / GROUPING SETS the totals/non-member rows emit the remaining keys as their column defaults, so the dropped key is recomputed as f(default) (toString(0) = '0') instead of the required column default (''), changing results. Same absent-key contract from OptimizeKeyExpressionsUtils.h the injective pass already guards.
c Fix matches root cause? Yes. Extends the existing CUBE/ROLLUP early-return guard to isGroupByWithGroupingSets() and isGroupByWithTotals(), mirroring the injective-functions pass in the same PR. No behavior change for plain GROUP BY / GROUP BY ALL.
d Test intent preserved / new tests added? Added regression cases to 04546_injective_functions_in_group_by_modifiers for optimize_group_by_function_keys: WITH TOTALS, GROUPING SETS, and a plain-GROUP BY case asserting the optimization still applies (result unchanged toggling the setting).
e Both directions demonstrated? Yes. Pre-fix: totals row v = '0'. Post-fix: totals row v = '', matching optimize_group_by_function_keys = 0. Full test passes through clickhouse-test.
f Fix is general across code paths? Yes. The two sibling passes (OptimizeGroupByInjectiveFunctionsPass, OptimizeGroupByFunctionKeysPass) are the two consumers of the OptimizeKeyExpressionsUtils.h absent-key contract; both now carry the identical modifier guard. LIMIT BY (the other util consumer) does not drop/rewrite keys based on this contract.
g Fix generalizes across inputs? The guard is on the query modifier (WITH TOTALS / GROUPING SETS / CUBE / ROLLUP), independent of key datatype or function; it fires before any type-specific handling, so all key types are covered.
h Backward compatible? Yes. Restores correct results; no setting default, format, or metadata change. The optimization still fires for plain GROUP BY (setting default unchanged).
i Invariants and contracts preserved? Yes. Upholds the OptimizeKeyExpressionsUtils.h invariant "a key is dropped only when it can still be computed from the keys that remain in every output row" — no longer violated for modifier rows that emit key defaults.

Session id: cron:clickhouse-worker-slot-1:20260716-190800

The new GROUPING SETS / WITH TOTALS guard in OptimizeGroupByFunctionKeysPass
correctly stops rewriting function keys under grouping sets, so the query-tree
in 02481_analyzer_optimize_grouping_sets_keys changes. Regenerated from the
fixed binary (Build ID f40246858).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai and others added 2 commits July 17, 2026 02:27
optimizeGroupBy and optimizeGroupByFunctionKeys in TreeOptimizer.cpp
(enable_analyzer=0) had no group_by_with_totals / grouping_sets bail-out,
so the totals/non-member rows recomputed a dropped function key from other
keys' defaults (toString(0)='0' instead of the String default ''). Mirror
the analyzer-pass guard and extend 04546 with enable_analyzer=0 cases.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
GROUP BY GROUPING SETS ((v, number), (number)) with ORDER BY number, v is
not a total order: for each number the member-set row (real v) and the
non-member-set row (v = default '') tie on both number and v, so they
interleaved nondeterministically between runs. Add GROUPING(v) as a final
ORDER BY key so the member-set row is always emitted before the non-member
row, yielding a stable result.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Covers the group_by_with_grouping_sets bail-out in the legacy
TreeOptimizer::optimizeGroupBy (injective path), mirroring the top-of-file
query-tree GROUPING SETS reproducer at enable_analyzer=0.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Single-set GROUPING SETS ((...)) never produces a non-member row: it is
collapsed to an ordinary GROUP BY by GroupingFunctionsResolvePass before
OptimizeGroupByFunctionKeysPass / OptimizeGroupByInjectiveFunctionsPass run,
so every output row still carries the key and the rewrite is safe. Both passes
must still fire for it, not be blocked by the GROUPING SETS guard added for the
multi-set case in ClickHouse#110715. Add two single-set queries proving the redundant
function-of-key is removed and the injective function is unwrapped.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Interpreters/TreeOptimizer.cpp Resolved
optimize_aggregators_of_group_by_keys eliminates min/max/any of a GROUP BY
key to the bare key. On the legacy AST path (enable_analyzer=0) the call site
skipped this only for WITH TOTALS / ROLLUP / CUBE, not GROUPING SETS, and
getGroupByKeysInfo unions all set members. So for GROUP BY GROUPING SETS
((a,b),(a)), max(b) was dropped to bare b and the (a)-set rows emitted b's
default 0 instead of the real aggregate. Add the group_by_with_grouping_sets
guard, matching the query-tree pass and the sibling optimizeGroupBy /
optimizeGroupByFunctionKeys guards. Add an enable_analyzer=0 regression.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The legacy-optimizer GROUP BY modifier guard (this PR) stops optimizeGroupBy
from eliminating the constant array key under WITH ROLLUP. Preserving the
heterogeneous array literal key makes the old analyzer validate it as a
Variant/Dynamic GROUP BY key and raise ILLEGAL_COLUMN (code 44) before the
function-argument type error. With allow_suspicious_types_in_group_by=1 the
same query still reaches ILLEGAL_TYPE_OF_ARGUMENT (43), confirming 44 is the
correct, more precise error, not a regression. Accept it alongside 43/386.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Interpreters/TreeOptimizer.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0d80e27

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, amd64/aarch64) / 00390_array_sort by-design (harness runs the changed test against the master binary which lacks this fix); both Bugfix-validation checks are themselves green not a failure
CH Inc sync - CH Inc sync (private, not actionable)

CI fully finished on this head: Config Workflow, Finish Workflow, Mergeable Check, CH Inc sync all green; zero check-level FAIL/ERROR rows. The prior PR-caused Fast-test / 00390 failures on earlier heads are resolved on 0d80e27.

Session id: cron:our-pr-ci-monitor:20260717-193000

@alexey-milovidov alexey-milovidov self-assigned this Jul 17, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

This is ok, but can we keep the optimization while fixing the values for rolled-up keys at the same time?
For example, we compute all normal keys as usual, but for rolled-up keys, just substitute the right defaults?
If you do, send another PR for that.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Will do - sending a separate follow-up PR that keeps the optimization and substitutes the correct type-defaults for the rolled-up / absent-key output rows (non-member GROUPING SETS rows, the WITH TOTALS row, CUBE/ROLLUP levels) instead of disabling it, across both analyzer passes and the legacy TreeOptimizer path. This PR stays as-is.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov For GROUPING SETS, CUBE and ROLLUP this works cleanly. Those rows carry the __grouping_set column, which is still present when the SELECT projection runs (PlannerExpressionAnalysis.cpp, available_columns_after_aggregation) and is exactly the signal grouping() uses to tell present vs rolled-up keys per set. So for an eliminated injective key f(g) the projection can emit if(<g rolled up in this row's set>, defaultOf(resultTypeOf(f(g))), f(g)): normal keys computed as usual, the correct output-type default for absent-key rows.

WITH TOTALS is different. The totals row is produced on a separate totals port (TotalsHavingTransform fills its key columns with type defaults) and carries no __grouping_set marker; the projection is applied to that port with no per-row signal, so there is no expression-level way to tell the totals row from a genuine g = default row. Keeping the optimization there would need a new marker threaded through the totals machinery, which is a larger, more invasive change.

Proposal: a follow-up PR re-enabling the optimization for GROUPING SETS / CUBE / ROLLUP with the grouping-conditioned default substitution above, keeping WITH TOTALS on the current bail-out. If you want WITH TOTALS covered too, I can add the totals-marker plumbing as a separate step. Which scope do you prefer?

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai

Keeping the optimization there would need a new marker threaded through the totals machinery, which is a larger, more invasive change.

Can we use ChunkInfo for that?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, ChunkInfo works. Verified:

  • The WITH TOTALS row is a distinct 1-row Chunk on a dedicated totals port (TotalsHavingTransform::prepareTotals).
  • The SELECT projection's ExpressionTransform preserves chunk_infos (it only detaches/sets columns; ISimpleTransform swaps the whole chunk), so a ChunkInfoCloneable marker attached to the totals chunk survives the projection intact. Same pattern as AggregatedChunkInfo.

One mechanic: the projection is an ActionsDAG over columns with no handle to the Chunk, so it cannot read the marker itself. The default substitution is done by a small transform on the totals port that consumes the marker and overwrites the eliminated injective-key columns with defaultOf(resultType(f)). That is the imperative form of "substitute the right defaults", and it is much smaller than threading a new signal through the aggregation machinery.

So the full scope is feasible and I will build it in the follow-up PR, keeping the optimization enabled: GROUPING SETS/CUBE/ROLLUP via the __grouping_set grouping-conditioned substitution, WITH TOTALS via the ChunkInfo marker. I will link the PR here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up PR opened: #110953. It keeps optimize_injective_functions_in_group_by enabled under the modifiers and substitutes the correct defaults for the absent-key rows.

For GROUPING SETS / CUBE / ROLLUP the correction is a grouping conditional over __grouping_set. For WITH TOTALS the totals row has no __grouping_set, so a small step after the projection overwrites the eliminated-key columns with their type default on the totals stream only. A ChunkInfo marker would also work, but it turned out unnecessary: the pipeline already routes the totals stream via StreamType::Totals (the same mechanism the HAVING/CUBE/ROLLUP steps use), so no new marker plumbing is needed.

Scope is the injective pass only; the function-keys pass stays disabled under the modifiers (removing a key changes the CUBE/ROLLUP lattice), as this PR does.

…y path

Address review: the new `optimize_aggregators_of_group_by_keys` guard in
`TreeOptimizer` also disabled the optimization for single-set
`GROUPING SETS ((...))`, although `ExpressionAnalyzer` classifies that
form as `GroupByKind::ORDINARY` (it is executed as a plain `GROUP BY`
and emits no rows with a key absent from the aggregated set), so the
min/max/any elimination is safe there. Narrow the guard to the multi-set
form and add an `enable_analyzer = 0` regression proving both the
unchanged result and that the `max(number) -> number` rewrite still
fires for the single-set form.

Co-Authored-By: Claude Fable 5 <[email protected]>
(number / 2, number / 3)
);

-- A single-set GROUPING SETS ((...)) never produces a non-member row: it is collapsed to an

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.

GROUPING SETS ((...)) is only collapsed to an ordinary GROUP BY when group_by_use_nulls = 0 (GroupingFunctionsResolvePass.cpp:182-188). With group_by_use_nulls = 1, the query still stays a grouping-sets query, resolveGroupByNode registers the key in nullable_group_by_keys, and the projection is re-resolved after GROUP BY to that Nullable key shape (QueryAnalyzer.cpp:3965-4016). AggregateFunctionOfGroupByKeysPass still rewrites max/min/any/anyLast to the bare key for grouping sets (AggregateFunctionOfGroupByKeysPass.cpp:38-86), so a query like SELECT toTypeName(max(number)) FROM numbers(1) GROUP BY GROUPING SETS ((number)) SETTINGS group_by_use_nulls = 1 can change from UInt64 to Nullable(UInt64).

So the new “single-set form is safe” proof is incomplete: it holds for group_by_use_nulls = 0, but not for the nullable-key path. This needs either a group_by_use_nulls bail-out in AggregateFunctionOfGroupByKeysPass for grouping sets, or a focused regression that proves max(key) keeps its original type under GROUPING SETS ((key)) SETTINGS group_by_use_nulls = 1.

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.

Verified on the current head (5cc0338): this type change is pre-existing master behavior, not something this PR introduces or that alexey's single-set narrowing affects.

  • AggregateFunctionOfGroupByKeysPass.cpp is byte-identical to master here (git diff master HEAD = 0 lines); it was last touched in Jan 2026. This PR does not modify it, and alexey's 5cc0338 only narrowed the legacy TreeOptimizer guard (enable_analyzer=0), while your repro is the analyzer path (enable_analyzer=1).
  • The flip reproduces with this PR's own passes disabled (optimize_injective_functions_in_group_by=0, optimize_group_by_function_keys=0), so those passes are not involved.
  • It is also arguably not a correctness bug: under group_by_use_nulls=1 the grouping key number is itself Nullable(UInt64) (SELECT toTypeName(number) ... GROUP BY GROUPING SETS ((number)) SETTINGS group_by_use_nulls=1), so rewriting max(number) to the bare key inherits that nullable type. Values are identical with the optimization on and off (0,1,2); only the declared type differs.

So there is no gap in the single-set narrowing on this PR's paths. Any change to AggregateFunctionOfGroupByKeysPass's group_by_use_nulls handling would be an independent, out-of-scope change to stock master code. Deferring to alexey, who is actively iterating on this PR.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and out of scope for this PR. Reproduced on this head with clickhouse local:

SELECT toTypeName(max(number)) FROM numbers(1) GROUP BY GROUPING SETS ((number)) SETTINGS group_by_use_nulls=1, optimize_aggregators_of_group_by_keys=0  -- UInt64
                                                                                                     ... optimize_aggregators_of_group_by_keys=1  -- Nullable(UInt64)
SELECT toTypeName(number)      FROM numbers(1) GROUP BY GROUPING SETS ((number)) SETTINGS group_by_use_nulls=1  -- Nullable(UInt64)

The values are identical with the optimization on and off (0,1,2); only the declared type differs, and it differs because the grouping key number is itself Nullable(UInt64) under group_by_use_nulls=1, so rewriting max(number) to the bare key inherits that type. AggregateFunctionOfGroupByKeysPass is not modified by this PR (byte-identical to master), and the flip also reproduces with this PR's own passes (optimize_injective_functions_in_group_by, optimize_group_by_function_keys) disabled. So this is pre-existing master behavior, not a regression introduced here, and it does not block this PR. If the Nullable-key type under group_by_use_nulls=1 is deemed worth changing, it should be a separate change to AggregateFunctionOfGroupByKeysPass.

@groeneai

groeneai commented Jul 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5cc0338

Every failed check below has an owner. Only CH Inc sync is exempt.

CI is fully finished on this head (Finish Workflow SUCCESS 2026-07-19 21:40:29Z; Config Workflow + CH Inc sync green; 0 queued/in-progress; >20 min buffer). No PR-caused failure remains on this head.

Check / test Reason Owner
Bugfix validation (functional tests, amd64 + aarch64) / 00390_array_sort by-design: check_status = success, xfail-inverted (the master-HEAD half of bugfix validation is expected to fail) Not a failure. 00390_array_sort is OK on all 22 real Stateless jobs on this head (incl. amd_debug, amd_tsan, amd_msan WasmEdge, amd_llvm_coverage old-analyzer WasmEdge) + 250 flaky-check runs.
BuzzHouse (amd_tsan) / Not-ready Set is passed as the second argument (STID 0250-41a5) chronic trunk (12 master + 131 distinct PRs in 30d) trunk tracker #107619
Stateless tests (arm_binary, parallel) / 01730_distributed_group_by_no_merge_order_by_long chronic trunk flaky, MEMORY_LIMIT (17 master + 162 distinct PRs in 30d) under @ alexey-milovidov active investigation (separate fix PR)
Sync - CH Inc sync (private, not actionable)

Session id: cron:clickhouse-maint-slot-8:20260719-223800

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 24535c9

CI is fully finished on this head (Finish Workflow SUCCESS, CH Inc sync green, 0 queued/in-progress, >20 min buffer). No PR-caused failure remains: 00390_array_sort in Bugfix validation is not a failure (the check itself is success), and every other red is a pre-existing trunk issue with an owner.

Check / test Reason Owner
Bugfix validation (functional tests, amd64 + aarch64) / 00390_array_sort by-design: check_status = success, xfail-inverted (the master-HEAD half of bugfix validation is expected to fail). 00390_array_sort is OK on all 262 real Stateless runs on this head. Not a failure
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter chronic trunk flaky (121 master + 30+ distinct unrelated PRs in 30d) #111029 (ours, open) / issue #110036
Stateless tests (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, parallel, 2/3) / STID 2735-47bf + Server died chronic trunk: the multiply(Int256, Float64) type-mismatch abort from a 03915_exchange_tables_race.sh TOCTOU under the old analyzer (the !part.empty() CIDB label is a scraper misattribution to a co-located comment). 0 master, ~34 distinct unrelated PRs in 30d. #109747 (ours, open) / issue #110133
Stress test (amd_debug) / Hung check failed, possible deadlock found chronic hung-check family (MEMORY_LIMIT_EXCEEDED connection retries under the thread-fuzzer stress harness) #108212 (ours, merged) / #105905 (ours, merged)
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260722-200000

@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 082731b

CI is fully finished on this head (Finish Workflow success, 156 success / 18 skipped, zero failures).
No failed check, so there is nothing to own.

Session id: cron:our-pr-ci-monitor:20260726-163000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit cc34c90 Jul 31, 2026
178 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 31, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.1, 26.2, 26.3, 26.4, 26.5, 26.6. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 31, 2026
Resolves the conflict in OptimizeGroupByInjectiveFunctionsPass.cpp. Master gained
a87ae3f (ClickHouse#110721), which disables the injective GROUP BY unwrap under
GROUPING SETS / WITH TOTALS / CUBE / ROLLUP because the rewrite makes the output
projection recompute f(defaultOf(g)) on rows where the key is absent from the set
being aggregated.

This branch supersedes that guard: it keeps the unwrap under those modifiers and
corrects the absent-key output rows instead, via a grouping conditional for
CUBE / ROLLUP / GROUPING SETS and a totals-stream overwrite for plain WITH TOTALS.
Master's whole change to this file is the guard inside the conflicting hunk, so
the resolution takes this branch's version of the pass unchanged.

ClickHouse#110721's other files (OptimizeGroupByFunctionKeysPass.cpp, TreeOptimizer.cpp and
its tests, including 04546) are untouched by this branch and are preserved as
merged on master.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 31, 2026
…2969 reference

Two post-merge corrections, both verified against a build of the merged tree.

ColumnNode's column-source parameter type was renamed from QueryTreeNodeWeakPtr to
TableExpressionNodeWeakPtr on master (88b22b8, "Introduce ITableExpressionNode
in the query tree"), so the __grouping_set column this pass synthesizes no longer
compiled. GroupingFunctionsResolvePass, which this code mirrors, uses the new name
in the same position.

02969's reference was auto-merged to master's variant, which records the query tree
with the injective unwrap DISABLED (the state ClickHouse#110721 produced). This branch keeps
the unwrap and corrects the totals row instead, so the tree dump has to show the
unwrapped GROUP BY key again. The restored file is byte-identical to the merged
build's actual output. Only the tree dump differs from master; the data assertion
that the WITH TOTALS row prints the String default rather than '0' is unchanged and
is what both branches fix.

Co-Authored-By: Claude Opus 4.8 <[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 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.

optimize_injective_functions_in_group_by changes the WITH TOTALS row value of a computed grouping key

5 participants