Skip to content

Support group_by_use_nulls in WITH TOTALS - #107106

Open
groeneai wants to merge 37 commits into
ClickHouse:masterfrom
groeneai:groeneai/rebase-39574-group-by-use-nulls-totals
Open

groeneai wants to merge 37 commits into
ClickHouse:masterfrom
groeneai:groeneai/rebase-39574-group-by-use-nulls-totals

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

GROUP BY ... WITH TOTALS now respects the group_by_use_nulls setting: the GROUP BY keys in the TOTALS summary row are reported as NULL instead of their default values, consistent with GROUPING SETS, ROLLUP and CUBE. Keys whose types cannot be wrapped in Nullable (for example Array or Map) keep their default value. Disabling the new setting group_by_use_nulls_with_totals (or compatibility before 26.11) restores the previous behavior.

Description

Port of #39574 (original author @ novikd) to current master.

With group_by_use_nulls = 1, GROUP BY keys are already reported as Nullable for GROUPING SETS, ROLLUP and CUBE, but plain GROUP BY ... WITH TOTALS was left out: the keys stayed non-nullable and the TOTALS summary row showed 0 (the default value) instead of NULL.

This ports the original fix to the analyzer and planner:

  • IdentifierResolveScope: resolve the keys, and the expressions over them, as Nullable for WITH TOTALS too.
  • PlannerExpressionAnalysis: include WITH TOTALS in the group_by_use_nulls condition so the result type of the keys is analyzed as Nullable.
  • Planner: insert a toNullable conversion for the GROUP BY keys before the TotalsHaving step. The TOTALS row is filled from default values, so a Nullable key column yields NULL there. This also covers CUBE/ROLLUP WITH TOTALS, whose own conversion runs after TotalsHaving.
  • OptimizeLimitByInjectiveFunctionsPass: register the Nullable shape of the WITH TOTALS keys too, as for ROLLUP/CUBE/GROUPING SETS, so LIMIT BY is not unwrapped past a key (that failed with NOT_FOUND_COLUMN_IN_BLOCK).
  • FunctionToSubcolumnsPass: skip the subcolumn rewrite for WITH TOTALS, as for ROLLUP/CUBE/GROUPING SETS (a key spelled tupleElement(tup, 'a') failed with NOT_FOUND_COLUMN_IN_BLOCK).
  • New setting group_by_use_nulls_with_totals (default 1, 0 with compatibility before 26.11) gates all of the above; when disabled, the previous result shape is kept.

Example (before this change the last row was 0):

SELECT number FROM numbers(10) GROUP BY number WITH TOTALS ORDER BY number SETTINGS group_by_use_nulls = 1;
-- 0 .. 9
--
-- \N

Upgrade note: a single-shard remote/Distributed query with group_by_use_nulls = 1 and WITH TOTALS from an older initiator fails with CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN unless the upgraded servers set group_by_use_nulls_with_totals = 0 until every node is upgraded.

Tests: new 02373_group_by_use_nulls_with_totals (from #39574) and 05355_group_by_use_nulls_with_totals_setting; updated references of seven existing tests.


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

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT number FROM numbers(10) GROUP BY number WITH TOTALS ORDER BY number SETTINGS group_by_use_nulls=1 (and the CUBE/ROLLUP variants) deterministically show the TOTALS row key as 0 on master and \N with the fix. Verified with the master debug binary (unfixed) vs the patched binary at the same HEAD fc73f46.
b Root cause explained? group_by_use_nulls makes GROUP BY keys Nullable so the extra summary row produced by GROUPING SETS/ROLLUP/CUBE/WITH TOTALS reports keys as NULL. The analyzer condition in PlannerExpressionAnalysis only listed grouping-sets/rollup/cube, so plain WITH TOTALS keys were typed and emitted non-nullable; the TotalsHaving step fills the summary row from default values, giving 0 instead of NULL.
c Fix matches root cause? Yes. Two targeted changes: (1) add WITH TOTALS to the group_by_use_nulls gate so the keys are analyzed as Nullable; (2) insert a toNullable conversion of the keys right before the TotalsHaving step so the data matches the analyzed type and the default-filled TOTALS row becomes NULL.
d Test intent preserved / new tests added? Yes. New regression test 02373_group_by_use_nulls_with_totals (from the original PR). Updated 02343/02535/03912 references to the now-correct \N TOTALS rows; no assertions weakened. Affected tests pin enable_analyzer=1 (analyzer-only behavior).
e Both directions demonstrated? Yes. Unfixed master binary: TOTALS row = 0 (test FAILS). Patched binary: TOTALS row = \N (test PASSES). Confirmed for plain/CUBE/ROLLUP WITH TOTALS, and that plain GROUP BY without TOTALS and group_by_use_nulls=0 are unchanged.
f Fix is general, not a narrow patch? Yes. The conversion is keyed on the aggregation keys (not one query shape) and covers plain/CUBE/ROLLUP WITH TOTALS uniformly; GROUPING SETS WITH TOTALS was already correct and is unaffected. Keys that cannot be Nullable are skipped via canBeInsideNullable. No symmetric path left unfixed. Old (non-default) analyzer is out of scope and the tests are pinned to the analyzer.

Session id: cron:clickhouse-worker-slot-23:20260610-225430

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vdimir — could you review this? It rebases #39574 and ports the group_by_use_nulls + WITH TOTALS fix to the analyzer: the TOTALS summary row now reports GROUP BY keys as NULL (matching GROUPING SETS/ROLLUP/CUBE) by typing the keys Nullable in PlannerExpressionAnalysis and adding a toNullable conversion just before the TotalsHaving step. Original authorship credited to @novikd in the commit.

@pufit pufit added the can be tested Allows running workflows for external contributors label Jun 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [15bce85]

Summary: ✅


AI Review

Summary

Reviewed PR #107106 at 15bce85d1013de2c4f8a95f4284b37771028650c, including the full diff and all prior discussion. The change extends group_by_use_nulls to WITH TOTALS, with group_by_use_nulls_with_totals and its 26.11 compatibility history preserving the previous behavior when required. No actionable findings remain after checking the current implementation and regression coverage against the earlier review threads.

Nullable-output consumers traced:

  • TotalsHavingTransform creates the totals keys from the converted header and preserves aggregate-state handling; the preceding ExpressionTransform retains overflow metadata.
  • RollupStep, CubeStep, and their transforms derive merge headers from the converted input and use nullable-aware wrapping.
  • Projection, HAVING, QUALIFY, sorting, window functions, and LIMIT BY consume the analyzed nullable types; window aggregate bindings account for argument-type changes.
  • Correlated references use their owning scope's nullable-key registrations. The subcolumn and injective-function passes include the new setting gate.
  • Distributed aggregation converts keys after merging and reconstructing the aggregation header. The documented compatibility setting preserves the previous result shape during upgrades.
Missing context / blind spots
  • ⚠️ On 2026-11-18, the current CI workflow is still running: Fast test has passed, while targeted stateless tests and much of the remaining matrix are pending. Final CI results will close this validation gap. No local build or runtime tests were performed in this review.
Final Verdict

Status: ✅ Approve. No new inline findings or thread-state changes are needed; the remaining CI checks must complete through the normal merge gates.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 11, 2026
Comment thread src/Planner/Planner.cpp Resolved
@groeneai
groeneai force-pushed the groeneai/rebase-39574-group-by-use-nulls-totals branch 2 times, most recently from 7507ca2 to a54354e Compare June 11, 2026 02:28
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated after addressing review)

# Question Answer
a Deterministic repro? Yes. SELECT number AS k, k IS NULL, count() FROM numbers(3) GROUP BY k WITH TOTALS ORDER BY k SETTINGS group_by_use_nulls = 1, enable_analyzer = 1 deterministically produced \N 0 3 in the TOTALS row before the fix (and toTypeName(k) reported UInt64); the original symptom was the TOTALS key printing 0 instead of NULL.
b Root cause explained? Two gates select which GROUP BY modifiers get group_by_use_nulls handling and both listed only GROUPING SETS / ROLLUP / CUBE. (1) The planner never typed plain-TOTALS keys Nullable nor inserted a conversion, so the TOTALS row (built from insertDefaultInto) emitted 0. (2) IdentifierResolveScope never enabled group_by_use_nulls for plain TOTALS, so the query tree resolved keys and expressions over them as non-nullable, making k IS NULL fold to 0 and toTypeName(k) report the non-nullable type.
c Fix matches root cause? Yes. Adds isGroupByWithTotals() to both gates (IdentifierResolveScope and PlannerExpressionAnalysis) and inserts a toNullable conversion of the GROUP BY keys right before TotalsHaving in Planner. The analyzer types the contract, the planner makes the runtime data match it.
d Test intent preserved / new tests added? New test 02373_group_by_use_nulls_with_totals covers plain / mixed / constant-key cases including type observation via k IS NULL. References for 02343, 02535, 03912 updated to the corrected TOTALS rows. No existing assertions weakened.
e Both directions demonstrated? Yes. Unpatched master build: TOTALS row 0 / k IS NULL = 0 / toTypeName = UInt64. Patched build: TOTALS row \N / k IS NULL = 1 / toTypeName = Nullable(UInt64), matching CUBE/ROLLUP WITH TOTALS.
f Fix is general, not a narrow patch? Yes. The fix targets the two shared gates that all GROUP BY modifiers flow through, so it stays consistent with the existing GROUPING SETS / ROLLUP / CUBE handling rather than being a one-off. A/B run of every local-runnable totals/rollup/cube/grouping_sets stateless test against an unpatched master build: 121 identical, only the 4 intended group_by_use_nulls + WITH TOTALS tests differ. Folded constant keys are documented as intentionally outside the NULL contract (uniform with the other modifiers).

Session id: cron:clickhouse-worker-slot-15:20260611-020200

@groeneai
groeneai force-pushed the groeneai/rebase-39574-group-by-use-nulls-totals branch from a54354e to a458d3e Compare June 11, 2026 03:39
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Re-run for the test coverage update (a458d3e), which adds expression-level cases to 02373_group_by_use_nulls_with_totals per the review comment.

# Question Answer
a Deterministic repro? Yes. On a build with only the IdentifierResolveScope hunk reverted, clickhouse-test 02373_group_by_use_nulls_with_totals fails deterministically; the diff is confined to the new expression-level lines (toTypeName(k): Nullable(UInt64)→UInt64, k IS NULL in the TOTALS row: 1→0).
b Root cause explained? The fix has two layers: the Planner step inserts a runtime toNullable so the TOTALS row carries a NULL value, and IdentifierResolveScope/PlannerExpressionAnalysis type the key as Nullable in the query tree. The old test only asserted the raw value, which the Planner layer alone produces, so the query-tree typing layer was unprotected: toTypeName(k) and k IS NULL are resolved against the analyzed type, so without the scope change they report the non-nullable type and fold IS NULL to 0.
c Fix matches root cause? The change is test-only. It adds toTypeName(k), k IS NULL, and a wrapping-subquery case that depend on the analyzed (query-tree) type, directly covering the IdentifierResolveScope layer the bot flagged. No source change.
d Test intent preserved / new tests added? Preserved and extended. The pre-existing raw-value, pure-constant-key, and mixed-key cases are unchanged; three expression-level assertions are added on top.
e Both directions demonstrated? Yes. With the full fix: 30/30 passes under --test-runs 30 (randomization on) and 20/20 on a follow-up run. With only the IdentifierResolveScope hunk reverted (Planner + PlannerExpressionAnalysis kept): the runner reports [ FAIL ] with the diff isolated to the new expression-level lines, while the raw-value lines still match. Binary identity verified by Build ID (fix 706cc63… vs reverted a38aebcd…).
f Fix is general, not a narrow patch? N/A for the source fix in this round (unchanged). The underlying fix already covers all three layers (scope typing, expression analysis result type, planner runtime conversion) and the analogous GROUPING SETS/ROLLUP/CUBE paths; this round only adds the regression test that guards the scope-typing layer.

Session id: cron:clickhouse-worker-slot-31:20260611-030000

@groeneai
groeneai force-pushed the groeneai/rebase-39574-group-by-use-nulls-totals branch from a458d3e to 878b0ce Compare June 11, 2026 04:28
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (docs follow-up, head 878b0ce)

This commit is a docs-only follow-up to the clickhouse-gh[bot] change-request: align the user-facing docs with the new WITH TOTALS + group_by_use_nulls behavior. No code logic changed (only the Settings.cpp raw-string setting description and a Markdown doc).

# Question Answer
a Deterministic repro? N/A (docs-only change; no runtime behavior altered). The behavior being documented is already deterministically covered by test 02373_group_by_use_nulls_with_totals (raw key value, pure constant key, mixed real+constant key, toTypeName(k)/k IS NULL, wrapping subquery).
b Root cause explained? The PR makes real GROUP BY keys Nullable and reported as NULL in the WITH TOTALS summary row under group_by_use_nulls = 1, but the docs still described the old contract: the group_by_use_nulls setting text in src/Core/Settings.cpp listed only ROLLUP/CUBE/GROUPING SETS, and the WITH TOTALS section in group-by.md still said key columns hold default values.
c Fix matches root cause? Yes. Both flagged docs now state the new behavior and the folded-constant-key exception: Settings.cpp adds WITH TOTALS to the modifier list plus a sentence on the NULL/Nullable totals-row behavior; group-by.md WITH TOTALS section adds the same with a link to the setting.
d Test intent preserved / new tests added? N/A for docs. The doc statements match existing test 02373 (constant key keeps its value; real key becomes NULL). No test change in this follow-up.
e Both directions demonstrated? N/A (docs-only). Verified src/Core/Settings.cpp still compiles after editing the raw-string description (src/CMakeFiles/dbms.dir/Core/Settings.cpp.o built clean).
f Fix is general, not a narrow patch? Yes. Audited all docs mentioning WITH TOTALS/group_by_use_nulls: settings.md has no separate prose (auto-generated from Settings.cpp); the format docs (Pretty/JSON/TabSeparated/Template, index.md) only describe totals-row output formatting, not the key-column value contract. The two places that describe that contract are exactly the two updated.

Session id: cron:clickhouse-worker-slot-4:20260611-042300

@groeneai
groeneai force-pushed the groeneai/rebase-39574-group-by-use-nulls-totals branch from 878b0ce to a7eba4d Compare June 11, 2026 06:05
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

For the GROUP BY ALL WITH TOTALS fix (commit a7eba4d):

# Question Answer
a Deterministic repro? Yes. SELECT k, toTypeName(k) FROM (SELECT number AS k FROM numbers(3) GROUP BY ALL WITH TOTALS) WHERE k IS NULL SETTINGS group_by_use_nulls = 1, enable_analyzer = 1; threw NOT_AN_AGGREGATE on every run on the PR head before this fix; SELECT number AS k, toTypeName(k), k IS NULL FROM numbers(3) GROUP BY ALL WITH TOTALS ORDER BY k SETTINGS group_by_use_nulls = 1 reproduced it directly.
b Root cause explained? Yes. With group_by_use_nulls, resolveQuery skips early projection resolution and resolveGroupByNode does not run for GROUP BY ALL (its key list is empty until expandGroupByAll, which runs near the end of resolveQuery). So no keys are registered in nullable_group_by_keys, the projection is typed non-nullable, and validateAggregates compares it against keys it converted to Nullable, raising NOT_AN_AGGREGATE. The new isGroupByWithTotals gate routed ordinary WITH TOTALS (incl. GROUP BY ALL) onto this delayed-resolution path, exposing the gap.
c Fix matches root cause? Yes. resolveQuery now expands GROUP BY ALL before resolveGroupByNode registers the nullable keys when group_by_use_nulls is set, so the keys are registered and the projection is typed Nullable. No widened bounds or suppression tags.
d Test intent preserved / new tests added? Yes. Added two GROUP BY ALL WITH TOTALS cases to 02373_group_by_use_nulls_with_totals (the bot's wrapping subquery, and toTypeName(k) / k IS NULL), guarding the expansion-order fix. No existing assertions weakened.
e Both directions demonstrated? Yes. PR head before fix: NOT_AN_AGGREGATE. With fix: \N / Nullable(UInt64), matching explicit GROUP BY k WITH TOTALS. 02373 matches its reference exactly, 30/30 with randomization; sibling tests 02343/02535/03912 and GROUP BY ALL suite tests 02459/03298/03413/03453 still pass.
f Fix is general, not a narrow patch? Yes. Fix is at the resolution-order source, not a guard at the symptom. It covers the whole GROUP BY ALL modifier family: GROUP BY ALL WITH ROLLUP/CUBE + group_by_use_nulls (which hit the same NOT_AN_AGGREGATE even on master) now also work. Explicit GROUP BY and group_by_use_nulls = 0 paths are unchanged.

Session id: cron:clickhouse-worker-slot-8:20260611-051100

@groeneai
groeneai force-pushed the groeneai/rebase-39574-group-by-use-nulls-totals branch from a7eba4d to 92e774a Compare June 11, 2026 06:43
Rebase and port of ClickHouse#39574 (original author @novikd) to the analyzer.

With group_by_use_nulls enabled, GROUP BY keys are reported as Nullable
for GROUPING SETS, ROLLUP and CUBE, but plain GROUP BY ... WITH TOTALS was
left out: the keys stayed non-nullable and the TOTALS summary row showed 0
instead of NULL.

The original PR fixed this in the old interpreter by converting the keys
inside AggregatingStep. The analyzer is now the default and needs the same
behavior, so this ports the fix to the analyzer in two places that gate the
group_by_use_nulls handling on the GROUP BY modifier and previously listed
only GROUPING SETS / ROLLUP / CUBE:

* IdentifierResolveScope: include WITH TOTALS so the query tree resolves the
  GROUP BY keys (and expressions over them) as Nullable. Without this the
  planner-side conversion below produces a Nullable key column at runtime
  while query-tree analysis still treats the key as non-nullable, e.g.
  'k IS NULL' over the TOTALS row folds to 0 and toTypeName(k) reports the
  non-nullable type, and a wrapping subquery sees the wrong key type.
* PlannerExpressionAnalysis: include WITH TOTALS so the result type of the
  keys is analyzed as Nullable, consistent with the scope above.
* Planner: insert a toNullable conversion for the GROUP BY keys right before
  the TotalsHaving step. The TOTALS row is built from default values, so a
  Nullable key column yields NULL there. This runs for CUBE/ROLLUP WITH
  TOTALS as well, because their own nullable conversion happens after
  TotalsHaving and would otherwise leave the TOTALS row non-NULL. Keys that
  cannot be made Nullable are skipped.

GROUP BY ALL needs an extra step. Its key list is empty until expandGroupByAll
collects the keys from the projection, and that normally runs near the end of
resolveQuery, after resolveGroupByNode is the only place that registers keys
in nullable_group_by_keys. So with the new WITH TOTALS gate, GROUP BY ALL took
the delayed-resolution path with no registered keys: the projection was typed
non-nullable while validateAggregates compared it against keys it had converted
to Nullable, raising NOT_AN_AGGREGATE. resolveQuery now expands GROUP BY ALL
before resolveGroupByNode when group_by_use_nulls is set. The expansion uses a
throwaway clone of the projection so the real projection keeps its aliases and
is not constant-folded against the pre-nullable types; the clone's resolved key
nodes still match the real keys structurally, because nullable_group_by_keys
ignores aliases and types. GROUP BY ALL WITH TOTALS then behaves exactly like
the explicit GROUP BY case, and GROUP BY ALL WITH ROLLUP/CUBE (which had the
same NOT_AN_AGGREGATE error before) works too.

Constant GROUP BY keys are folded away before aggregation and are not real
key columns, so they keep their constant value in the TOTALS row instead of
becoming NULL. This is the same as CUBE/ROLLUP/GROUPING SETS WITH TOTALS,
where a folded constant key likewise stays constant in the summary rows.

02373 covers the raw key value in the TOTALS row, a pure constant key, and a
mixed real plus constant key. It also covers the expression level so the
IdentifierResolveScope typing is protected: toTypeName(k) over the WITH
TOTALS result, 'k IS NULL' which is 1 in the TOTALS row, and a wrapping
subquery that selects the TOTALS row with WHERE k IS NULL. Without the
IdentifierResolveScope change these report the non-nullable type and fold
'k IS NULL' to 0 while the raw value cases still pass, so they are the
regression guard for that part of the fix. The same expression-level cases
are added for GROUP BY ALL WITH TOTALS as the regression guard for the
expansion-order fix above.

Documentation: the group_by_use_nulls setting text in src/Core/Settings.cpp
and the WITH TOTALS section in docs/en/sql-reference/statements/select/group-by.md
now state that with group_by_use_nulls = 1 the real GROUP BY keys in the WITH
TOTALS row are reported as NULL, qualified to only keys whose types can be
wrapped in Nullable. Keys whose types cannot be made Nullable (for example
Array and Map, which fail canBeInsideNullable) keep their default value, as
does a folded constant key.

The behavior is analyzer-only; the affected tests set enable_analyzer = 1.

Co-authored-by: Dmitry Novik <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/rebase-39574-group-by-use-nulls-totals branch from 92e774a to 0d313cb Compare June 11, 2026 06:44
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

This round addresses the clickhouse-gh[bot] change-request on docs/.../select/group-by.md (review comment 3393695403): the docs over-promised that every real GROUP BY key becomes NULL in the totals row. Docs-only delta, no behavior change.

# Question Answer
a Deterministic repro? Yes (behavioral confirmation of the gap the docs mis-stated). Array/Map keys with group_by_use_nulls=1, enable_analyzer=1: SELECT [number] AS k, toTypeName(k) FROM numbers(3) GROUP BY k WITH TOTALS -> totals row [] Array(UInt64) (default, not NULL) on every run; scalar UInt64 key -> \N Nullable(UInt64).
b Root cause explained? addConvertGroupByKeysToNullableStep (src/Planner/Planner.cpp:843) only inserts toNullable for keys where removeLowCardinality(type)->canBeInsideNullable() is true. DataTypeArray::canBeInsideNullable() and DataTypeMap::canBeInsideNullable() return false, so those keys keep their default in the totals row. The docs claimed all real keys become NULL, which is inaccurate for these types.
c Fix matches root cause? Yes. Docs now state only keys whose types can be wrapped in Nullable are converted/reported as NULL; Array/Map (and other non-canBeInsideNullable types) keep their default value. Matches the canBeInsideNullable gate exactly.
d Test intent preserved / new tests added? N/A (docs-only). The runtime behavior is unchanged and already covered by 02373_group_by_use_nulls_with_totals for the convertible-key case. No code change, so no new regression test needed.
e Both directions demonstrated? N/A bidirectional (docs-only, no behavior change). Empirically verified the documented behavior matches the implementation (Array/Map keep default; scalar keys become NULL), shown in (a).
f Fix is general, not a narrow patch? Yes. Both places stating the totals-row key-value contract are qualified: docs/en/sql-reference/statements/select/group-by.md (WITH TOTALS section) and src/Core/Settings.cpp (group_by_use_nulls text, from which settings.md is auto-generated). Sibling audit: the format docs (Pretty/JSON/TabSeparated/Template, select/index.md) describe only totals-row output formatting, not the key value contract, so no further change needed.

Session id: cron:clickhouse-worker-slot-2:20260611-063900

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on 0d313cb726ca. The single non-passing functional check is a known-flaky test unrelated to this PR:

  • Integration tests (amd_tsan, 6/6) / test_profile_max_sessions_for_user_postgres - chronic flaky (15 distinct PRs + 2 master hits in the last 30 days). This PR is analyzer-only (group_by_use_nulls + WITH TOTALS) and does not touch session limits or PostgreSQL integration. Tracked separately; a dedicated fix PR (Fix flaky timeout in test_profile_max_sessions_for_user (postgres) #107086) is already in review. Not caused by this PR.

The remaining red marks (Mergeable Check, PR) are derivative aggregators of the above. All other checks pass.

Session: cron:our-pr-ci-monitor:20260611-120000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD 0d313cb726ca (Finish Workflow pass). The single failure — test_profile_max_sessions_for_user/test.py::test_profile_max_sessions_for_user_postgres in Integration tests (amd_tsan, 6/6) — is a known chronic flaky timeout (CIDB: 16 hits across 15 PRs, incl. 2 master, in 30d), unrelated to this group_by_use_nulls / WITH TOTALS change. It is already tracked (a separate fix PR is in flight). No PR-caused failures. Moving to review.

Session id: cron:our-pr-ci-monitor:20260611-160000

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, as the bad integration test is fixed, update the branch in this PR, so we will have a chance to merge it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov done. Branch updated to the latest master (merged 369a1269e02c); PR head is now 259fa05035ed. Clean merge, no conflicts; the 3-part analyzer/planner fix and the WITH TOTALS / GROUP BY ALL test cases are intact. Builds clean (debug, clang-21) and the group_by_use_nulls + WITH TOTALS / GROUP BY ALL repros and tests pass locally. CI is re-running.

Comment thread src/Planner/Planner.cpp Resolved
Every regression case for the WITH TOTALS key nullification was local, so the
initiator's second stage went untested. There the keys are converted after
MergingAggregated, i.e. the header the conversion looks them up in comes from
merging the shards' aggregation states rather than from a local AggregatingStep.

Measured against master 7d76bcd over two shards via
remote('127.0.0.{2,3}'): the TOTALS row there reports 0 / UInt64 / IS NULL = 0,
so this arm is a regression guard and not a restatement of the local cases. It
holds on 8 of 8 combinations of the randomized distributed settings
(prefer_localhost_replica, distributed_aggregation_memory_efficient and the two
group_by_two_level_threshold* floors), and 40 randomized runs of the file pass.
The group_by_use_nulls = 0 twin pins that the keys stay non-Nullable there.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 94f1c8e

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 (arm_msan) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID 2508-348f) pre-existing trunk defect in the DISTINCT-in-order sorted-stream assertion: DistinctSortedStreamTransform.cpp:184 over ColumnVector<short> with no Nullable layer, which is this bucket's own signature rather than a sibling's #118077 (ours, open)
Stress test (arm_release) / Logical error: 'Virtual row has different type for CAST(__table1.'json.b', 'String')' (STID 1637-39a7) pre-existing trunk defect: the sorting key expression's type depends on a session setting, so setVirtualRow is handed String where the header declares Nullable(String) #119385 (ours, open)
Mergeable Check, PR praktika aggregators rolling up the two rows above, not separate failures #118077 and #119385 (both ours, open)

Not caused by this pull request. Both signatures predate it and neither touches the code it
changes: this branch only adds group_by_use_nulls support to WITH TOTALS, while the arm_msan
abort is a sort-property propagation defect and the arm_release abort is a virtual-row type
mismatch on a JSON subcolumn CAST. Both aborts also fire on trees that do not carry this branch.

Session id: cron:our-pr-ci-monitor:20260911-093124

alexey-milovidov and others added 3 commits September 23, 2026 10:01
# Conflicts:
#	src/Planner/Planner.cpp
…r `group_by_use_nulls` in `WITH TOTALS`

The test was added on master after this PR and pinned the old behaviour, where
`group_by_use_nulls` did not reach the keys of the totals row. With this PR the
key is `Nullable` under `WITH TOTALS` and is `NULL` in the totals row, so the
two `WITH TOTALS` cases move out of the "unchanged" guard section and the
reference is updated accordingly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Parsers/ParserSelectQuery.cpp Resolved
groeneai and others added 2 commits October 2, 2026 13:34
…ulls docs

The old query analyzer was removed in 26.10 and `enable_analyzer = 0` is now
accepted and replaced with `1`, so the sentences saying that the old analyzer
keeps the default key value in the totals row described behavior that no
longer exists. Describe the behavior unconditionally in the `GROUP BY`
statement documentation and in the `group_by_use_nulls` setting text, and drop
the stale "analyzer-only" comment in 03912.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tive-unwrap pass

With this PR `group_by_use_nulls` also promotes the `GROUP BY` keys of a plain
`WITH TOTALS` query to `Nullable`, but `OptimizeLimitByInjectiveFunctionsPass`
registered the `Nullable` shape of a key only for `GROUPING SETS`, `ROLLUP` and
`CUBE`. So `LIMIT BY` was unwrapped past the key, for example:

    SELECT toString(number) AS s FROM numbers(3) GROUP BY toString(number)
    WITH TOTALS ORDER BY s LIMIT 1 BY s
    SETTINGS group_by_use_nulls = 1, optimize_injective_functions_in_group_by = 0

failed with NOT_FOUND_COLUMN_IN_BLOCK. Use the same condition as
`IdentifierResolveScope` and cover it in 05213. Also drop the stale
"only supported by the analyzer" setup from 02373.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits October 2, 2026 16:27
FunctionToSubcolumnsPass already opts out for ROLLUP, CUBE and GROUPING SETS
when group_by_use_nulls is set, because the rewrite is not prepared for keys
whose post-GROUP BY type is wrapped in Nullable. WITH TOTALS now takes the same
nullable-key path, so it needs the same opt-out. Without it a key spelled as
tupleElement(tup, 'a') was rewritten to tup.a in GROUP BY only and the query
failed with NOT_FOUND_COLUMN_IN_BLOCK (master returns the rows, and the same
query with WITH ROLLUP works).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
enable_analyzer is frozen at 1, so the pins select nothing and only widened
the diff against master; the queries are back to master's text.

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

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6368520

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
Performance Comparison (arm_release, master_head, 6/6) / datetime_comparison #2 dashboard confirmed_regression, client_time 0.248 -> 0.287 s (+15.7%), only +5.4% after the harness restarted both servers. The shard's own report flags no query slower (3 too long only, which does not gate in master_head mode). The query is SELECT count() FROM numbers(1000000000) WHERE materialize(now()) > toDateTime('2020-09-30 00:00:00'): no GROUP BY and no WITH TOTALS, so none of the analyzer and planner code this PR changes runs. CIDB flags the same query slower or unstable on 3 unrelated PRs in the last 30 days ClickHouse/performance-comparison#5 (external), the dashboard's confidence scoring for noisy queries
Mergeable Check, PR rollups, red only because of the row above ClickHouse/performance-comparison#5 (external), the same owner as the row above
Sync - CH Inc sync (private, not actionable by me)

All 146 check runs completed and Finish Workflow is green; the cancelled jobs belong to a duplicate PR run at this head that was cancelled within a minute of starting. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20261002-230431

alexey-milovidov and others added 2 commits October 10, 2026 08:28
…compatibility setting

Add `group_by_use_nulls_with_totals` (default `true`, `26.10` entry in the
settings history with previous value `false`). When disabled, or with
`compatibility` set to a version before `26.10`, `group_by_use_nulls` does not
affect `WITH TOTALS`, which keeps the previous result shape. This allows
mixed-version `remote` / `Distributed` queries to keep working during a
rolling upgrade.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
groeneai and others added 3 commits October 10, 2026 09:22
…ING SETS

With `group_by_use_nulls_with_totals = 0`, `ROLLUP`, `CUBE` and
`GROUPING SETS` still make the keys `Nullable` through `group_by_use_nulls`;
only the totals row falls back to default values. The setting description
said the keys keep their types unconditionally. Also mention the new setting
in the `WITH TOTALS` paragraph of the `GROUP BY` statement documentation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The 26.10 release branch has already been cut, so the new setting first ships in 26.11.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Blargian
Blargian removed the request for review from a team October 19, 2026 19:31
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a600b80

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
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 55 of 55 runs in the last 6 hours are red, on 53 PRs #126200 (mine, open)
Fast test (arm_darwin) / 05227_mutate_part_ahead_of_table_metadata_version_mergetree flaky, not from this PR (it changes WITH TOTALS under group_by_use_nulls, not mutations): the rewrite dropped the column: 1 instead of 0, because an empty part left by DETACH PARTITION is still read as active by clickhouse-local. It failed on 55 PRs since 2026-10-27 16:41 UTC, and passed in Fast test and 7 stateless jobs of this head #127925 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #126200, #127925 (the owners of the rows above)

CIDB has no other FAIL or ERROR row for this head.

Session id: cron:our-pr-ci-monitor:20261028-063004

@CLAassistant

CLAassistant commented Nov 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

alexey-milovidov and others added 2 commits November 13, 2026 11:01
…74-group-by-use-nulls-totals

Resolve the conflict in `src/Planner/Planner.cpp`: master moved the planner
step helpers into `src/Planner/PlannerSteps.cpp`/`PlannerSteps.h`. Take
master's `Planner.cpp`, move `addConvertGroupByKeysToNullableStep` into
`PlannerSteps.cpp` (declared in `PlannerSteps.h`), and keep its call before
`addTotalsHavingStep` in `Planner.cpp` together with the
`group_by_use_nulls`/`group_by_use_nulls_with_totals` setting declarations.

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-review-human PR origin: human review feedback on a groeneai PR pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants