Skip to content

Fix aggregate_functions_null_for_empty for non-Nullable result types - #99839

Merged
alexey-milovidov merged 2 commits into
masterfrom
fix-aggregate-functions-null-for-empty-non-nullable
Mar 18, 2026
Merged

alexey-milovidov merged 2 commits into
masterfrom
fix-aggregate-functions-null-for-empty-non-nullable

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 18, 2026 •

Copy link
Copy Markdown
Member

Closes #38738. Closes #38786.

Some aggregate functions (e.g., groupArray, sumMap) return types like Array or Map that cannot be inside Nullable. The aggregate_functions_null_for_empty setting was unconditionally wrapping all result types in Nullable via the OrNull combinator, causing an exception like:

Code: 43. DB::Exception: Nested type Array(UInt64) cannot be inside Nullable type.

Now the OrNull combinator checks canBeInsideNullable before wrapping, and skips the Nullable wrapper for incompatible types, returning the default value (e.g., empty array) instead.

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 aggregate_functions_null_for_empty setting to work with aggregate functions returning non-Nullable types such as Array or Map (e.g., groupArray, sumMap).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Medium Risk
Changes -OrNull combinator result typing/serialization paths for some aggregate functions, which can affect query result types and empty-input behavior (especially for Array/Map aggregates). Scope is contained to AggregateFunctionOrFill but impacts any query using aggregate_functions_null_for_empty or OrNull combinators.

Overview
Fixes -OrNull aggregate combinator to avoid wrapping result types in Nullable when canBeInsideNullable() is false (e.g., Array, Map), preventing exceptions under aggregate_functions_null_for_empty and instead returning the normal default value for empty input.

Updates AggregateFunctionOrFill to track whether the result is nullable and to correctly insert merge vs non-merge results into nullable columns. Tests are updated to expect topKOrNull to be valid with parameters, and a new stateless test covers empty-input behavior for non-Nullable-compatible result types (groupArray, sumMap) alongside NULL-returning aggregates.

Reviewed by Cursor Bugbot for commit 778f908. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.3.1.792

…Nullable types

Some aggregate functions (e.g., `groupArray`, `sumMap`) return types like
Array or Map that cannot be inside Nullable. The `aggregate_functions_null_for_empty`
setting was unconditionally wrapping all result types in Nullable via the
OrNull combinator, causing an exception.

Now the OrNull combinator checks `canBeInsideNullable` before wrapping, and
skips the Nullable wrapper for incompatible types, returning the default value
(e.g., empty array) instead.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [778f908]

Summary: ✅


AI Review

Summary

This PR fixes aggregate_functions_null_for_empty for aggregate functions whose result types cannot be wrapped into Nullable (for example Array/Map) by avoiding invalid wrapping in AggregateFunctionOrFill. The change is focused, aligns with the stated bug, and the added stateless coverage exercises both non-nullable-compatible and regular nullable-compatible result paths.

Missing context

  • ⚠️ No CI logs/results were provided in this review context.

ClickHouse Rules

Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
Safe rollout ✅
Compilation time ✅

Final Verdict

  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 18, 2026
…hrowing

The `OrNull` combinator now skips `Nullable` wrapping for types that
cannot be inside `Nullable`, so `topKOrNullState` no longer throws
`ILLEGAL_TYPE_OF_ARGUMENT`.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99839&sha=7b20176882cb107649b50cc440adc8898e64a3c0&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good change, good test.

@qoega qoega self-assigned this Mar 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.70% 83.80% +0.10%
Functions 23.90% 23.90% +0.00%
Branches 76.20% 76.30% +0.10%

PR changed lines: PR changed-lines coverage: 90.00% (18/20, 0 noise lines excluded)
Diff coverage report
Uncovered code

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Mar 18, 2026
Merged via the queue into master with commit f9849ac Mar 18, 2026
159 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-aggregate-functions-null-for-empty-non-nullable branch March 18, 2026 12:07
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 18, 2026
alexey-milovidov added a commit that referenced this pull request Mar 22, 2026
The `transform` function casts WHEN values to the expression type. When
WHEN values are Nullable (e.g. `CAST(NULL AS Nullable(Int32))`) but the
expression is non-Nullable, the cast fails with "Cannot convert NULL
value to non-Nullable type".

This became visible after #99839 made `aggregate_functions_null_for_empty`
produce Nullable result types for more aggregates, causing SQLLogic tests
to hit this path.

Fix by wrapping the entire `transform` attempt (array construction,
build, and execute) in a try-catch that falls through to the `multiIf`
path on type-related errors. The `multiIf` path handles Nullable WHEN
values correctly via `caseWhenEquals`.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100293&sha=f067c3bec9fe4a7a07e810a27c9587ea9f777bfb&name_0=PR&name_1=SQLLogic%20test

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Mar 22, 2026
The `transform` function casts WHEN values to the expression type. When
WHEN values are Nullable (e.g. `CAST(NULL AS Nullable(Int32))`) but the
expression is non-Nullable, the cast fails with "Cannot convert NULL
value to non-Nullable type".

This became visible after #99839 made `aggregate_functions_null_for_empty`
produce Nullable result types for more aggregates, causing SQLLogic tests
to hit this path.

Fix by wrapping the entire `transform` attempt (array construction,
build, and execute) in a try-catch that falls through to the `multiIf`
path on type-related errors. The `multiIf` path handles Nullable WHEN
values correctly via `caseWhenEquals`.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100293&sha=f067c3bec9fe4a7a07e810a27c9587ea9f777bfb&name_0=PR&name_1=SQLLogic%20test

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Mar 24, 2026
The `transform` function casts WHEN values to the expression type. When
WHEN values are Nullable (e.g. `CAST(NULL AS Nullable(Int32))`) but the
expression is non-Nullable, the cast fails with "Cannot convert NULL
value to non-Nullable type".

This became visible after #99839 made `aggregate_functions_null_for_empty`
produce Nullable result types for more aggregates, causing SQLLogic tests
to hit this path.

Fix by wrapping the entire `transform` attempt (array construction,
build, and execute) in a try-catch that falls through to the `multiIf`
path on type-related errors. The `multiIf` path handles Nullable WHEN
values correctly via `caseWhenEquals`.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100293&sha=f067c3bec9fe4a7a07e810a27c9587ea9f777bfb&name_0=PR&name_1=SQLLogic%20test

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 22, 2026
Two changes in response to ClickHouse#105470 (review):

1. Replace the silent `if (!buf) bail` in `UniquesHashSet::write` with
`chassert(buf)`. The `AggregateFunctionOrFill::insertResultIntoImpl`
change in commit 4187aa5 establishes the invariant that the source
state's `buf` is never null at serialise time. The previous bail-out
silently masked corruption rather than surfacing it; the assertion now
documents the invariant and fails loudly in debug / sanitiser builds if
it is ever broken again.

2. Add new regression test `04273_105462_uniq_state_or_null_rollup_consumers`
covering consumer paths not exercised by the original
`04262_105462_uniq_state_or_null_with_rollup` test. The original test
only reaches the `serialize`-driven final-projection path. Algunenano
pointed out four additional consumers that all relied on the same
corrupted `UniquesHashSet`:

- `<func>Merge` over the rollup-produced state column. Reaches
  `UniquesHashSet::merge` via `AggregateFunctionMerge::add`.
- `INSERT INTO AggregatingMergeTree`. Persists the rollup-produced state
  via `ColumnAggregateFunction::insertMergeFrom` ->
  `AggregatingSortedAlgorithm::AggregatingMergedData::addRow` ->
  `MergeTreeDataWriter::mergeBlock`.
- Two-level + multi-thread aggregator scheduling variants.
- `Memory` engine source confirms the regression is pipeline-level
  rather than `MergeTree`-specific.

The test also mirrors the first reproducer for `uniqStateOrDefault`,
since ClickHouse#99839 enabled the `*StateOrDefault` chain in the same way as
`*StateOrNull`.

Verified locally:
- Without the `OrFill` fix (binary from a sibling branch lacking commit
  4187aa5), reproducer 1 segfaults at `UniquesHashSet::merge:453` (stack
  trace captured during this work).
- With the `OrFill` fix, 100/100 randomised runs of the new test pass,
  50/50 randomised runs of `04262` still pass, and the AggregatingMergeTree
  reproducer is asserted via `uniqMerge(s)` rather than `count()` so the
  assertion is deterministic across `enable_parallel_replicas` and
  `max_insert_threads` randomisation.
@Algunenano
Algunenano requested a review from Copilot May 23, 2026 13:37

Copilot AI left a comment

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.

Pull request overview

Fixes aggregate_functions_null_for_empty / -OrNull combinator behavior for aggregate functions whose result types cannot be wrapped in Nullable (e.g., Array, Map), avoiding ILLEGAL_TYPE_OF_ARGUMENT and returning the type’s default value for empty inputs instead.

Changes:

  • Update -OrNull result type construction to skip Nullable(...) wrapping when the nested result type cannot be inside Nullable.
  • Fix -OrNull insertion logic to use insertMergeResultInto when emitting merge results into the nested column of a ColumnNullable.
  • Add stateless regression tests covering Array/Map aggregate results under aggregate_functions_null_for_empty, and update an existing combinator parameter test expectation.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/AggregateFunctions/Combinators/AggregateFunctionOrFill.h Makes -OrNull avoid illegal Nullable wrapping for non-nullable-compatible result types; corrects merge-result insertion into nullable wrapper.
tests/queries/0_stateless/04045_aggregate_functions_null_for_empty_non_nullable_result.sql Adds regression queries for aggregate_functions_null_for_empty with groupArray/sumMap and other aggregates on empty input.
tests/queries/0_stateless/04045_aggregate_functions_null_for_empty_non_nullable_result.reference Expected outputs for the new regression test (default values for non-nullable-compatible results; NULL where applicable).
tests/queries/0_stateless/01159_combinators_with_parameters.sql Removes the expected error for topKOrNullState(...) now that -OrNull no longer fails on non-nullable-compatible types.
tests/queries/0_stateless/01159_combinators_with_parameters.reference Updates expected type name output accordingly.

, nested_function{nested_function_}
, size_of_data{nested_function->sizeOfData()}
, inner_nullable{nested_function->getResultType()->isNullable()}
, result_is_nullable{createResultType(nested_function_->getResultType())->isNullable()}
@Algunenano

Copy link
Copy Markdown
Member

cursor review

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 778f908. Configure here.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The `transform` function casts WHEN values to the expression type. When
WHEN values are Nullable (e.g. `CAST(NULL AS Nullable(Int32))`) but the
expression is non-Nullable, the cast fails with "Cannot convert NULL
value to non-Nullable type".

This became visible after ClickHouse#99839 made `aggregate_functions_null_for_empty`
produce Nullable result types for more aggregates, causing SQLLogic tests
to hit this path.

Fix by wrapping the entire `transform` attempt (array construction,
build, and execute) in a try-catch that falls through to the `multiIf`
path on type-related errors. The `multiIf` path handles Nullable WHEN
values correctly via `caseWhenEquals`.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100293&sha=f067c3bec9fe4a7a07e810a27c9587ea9f777bfb&name_0=PR&name_1=SQLLogic%20test

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

5 participants