Skip to content

Add aggregate function gini - #112280

Merged
Manerone merged 20 commits into
ClickHouse:masterfrom
amirreza1307:add-gini-aggregate-function
Aug 6, 2026
Merged

Manerone merged 20 commits into
ClickHouse:masterfrom
amirreza1307:add-gini-aggregate-function

Conversation

@amirreza1307

@amirreza1307 amirreza1307 commented Jul 28, 2026 •

Copy link
Copy Markdown

Adds gini, an aggregate function for measuring inequality over finite, non-negative numeric values. Unlike arrayNormalizedGini, it works directly over a column and can be used naturally with GROUP BY, aggregate combinators, and distributed aggregation.

The state retains samples in their original numeric or decimal type and sorts them at finalization. It computes the coefficient from normalized adjacent pairwise differences in long double before returning Float64, avoiding early Float64 precision loss and overflow for large finite values while preserving one-unit differences in wide integers and decimals. The function uses O(n) memory per group, skips NaN values, rejects negative and infinite inputs, and returns NaN for fewer than two values or a zero sum.

Changelog category (leave one):

  • New Feature

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

Added aggregate function gini to calculate the Gini coefficient of finite, non-negative numeric values, including grouped and distributed aggregations.

@CLAassistant

CLAassistant commented Jul 28, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Calculates the Gini coefficient of a numeric column, a measure of
inequality in a distribution. The result ranges from 0 (perfect
equality) to a maximum approaching 1 as the group grows.

The state collects all values and sorts them at finalize time, so the
function consumes O(n) memory like quantileExact. Returns NaN when
there are fewer than 2 values or the sum of values is 0. NaN inputs
are skipped.

Co-Authored-By: Claude Fable 5 <[email protected]>
@amirreza1307
amirreza1307 force-pushed the add-gini-aggregate-function branch from 59ffa1d to bc8aa31 Compare July 28, 2026 12:38
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Jul 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0783f8e]

Summary: ✅


AI Review

Summary

This PR adds the aggregate function gini and the supporting NULL/combinator handling needed for -If, -State, -SimpleState, -Distinct, -ArgMin / -ArgMax, -OrDefault / -OrNull, and -Resample. I re-checked the current diff against the prior discussion and the current CI results, and I did not find a remaining correctness, compatibility, or test-coverage issue that warrants a new review comment in the current revision.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 29, 2026
Reject negative inputs so results stay in the documented range. Return NaN for all-NULL groups, matching groups with fewer than two values.
Keep values in their input type and normalize pairwise-difference accumulation to avoid `Float64` coercion, overflow, and cancellation.
@Manerone Manerone self-assigned this Jul 30, 2026
Compare results within a tolerance because floating-point rounding differs between Linux and Darwin.
@amirreza1307
amirreza1307 requested a review from a team as a code owner July 31, 2026 11:52
Reject oversized states consistently while adding, merging, serializing, and deserializing.
Restart CI after the unrelated STID 3293-4e7f failure and a hung `Fast test (arm_darwin)` job.
@amirreza1307

Copy link
Copy Markdown
Author

CI retry note: Stress test (arm_msan) hit the pre-existing AST-fuzzer failure STID 3293-4e7f (ColumnFunction::appendArgument, Nullable(UInt64) vs UInt64). It has also failed on direct master and eight unrelated PRs in the last 90 days. The matching fix is already in progress in #111993 by @groeneai.

Failure report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112280&sha=fbd211c67aeec22c995b54a7e978f1869000c953&name_0=PR&name_1=Stress%20test%20(arm_msan)

The same run also had Fast test (arm_darwin) stuck in its Run step for almost three hours. Since I do not have permission to cancel/re-run the upstream workflow directly, commit 5221dad6d12 restarts CI without changing the source tree.

@amirreza1307
amirreza1307 requested a review from Manerone August 1, 2026 07:40
Use the function-owned null adapter for both Nullable numeric inputs and Nullable(Nothing), so an empty state still finalizes to Float64 NaN.
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.50% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.70% -0.10%

Changed lines: Changed C/C++ lines covered: 143/170 (84.12%) · Uncovered code

Full report · Diff report

@Manerone
Manerone added this pull request to the merge queue Aug 6, 2026
Merged via the queue into ClickHouse:master with commit f75ec00 Aug 6, 2026
179 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 6, 2026
dhtclk added a commit that referenced this pull request Aug 6, 2026
dhtclk added a commit that referenced this pull request Aug 6, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @amirreza1307 @Manerone — this PR appears to contain a backward incompatible change but is categorized as New Feature.

Why: The nine combinator files changed here are shared by every aggregate function. AggregateFunctionNull.cpp:88 reads getArgumentsThatCanBeOnlyNull to decide whether to fold the aggregate into AggregateFunctionNothing; making -State/-OrFill/-Resample/-Distinct/-ArgMin forward the nested set means countIfOrNull(number, NULL) goes from UInt64 0 to Nullable(UInt64) NULL and sumIfResample(0,2,1)(number, NULL, number % 2) goes from a scalar NULL to Array(UInt64) [0,0], verified against the released 26.7.1.1 binary.

Suggested category: Backward Incompatible Change

Could you check if the changelog category should be updated? This helps users know what to expect when upgrading. Ignore this if the change is intentionally non-breaking.

@clickgapai

Copy link
Copy Markdown
Contributor

Hi @amirreza1307 @Manerone — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The description covers gini in detail but says nothing about the combinator changes, which alter the result type (and in some cases the value) of pre-existing expressions such as sumIfState(x, NULL), countIfOrNull(x, NULL) and sumIfResample(...)(x, NULL, k).

  • Suggested addition:

    Also: getArgumentsThatCanBeOnlyNull is now forwarded through the -State, -SimpleState, -If, -OrNull/-OrDefault, -Distinct, -Resample and -ArgMin/-ArgMax combinators, and AggregateFunctionCombinatorNull::tryTransformStateFunctionImpl returns the nested function unchanged when its argument types already match. This is required for giniState(NULL) and friends, but it also changes the result of pre-existing expressions where a second combinator is stacked on -If with a constant NULL filter: countIfOrNull(x, NULL) now returns NULL instead of 0, sumIfResample(0,2,1)(x, NULL, k) now returns [0,0] instead of a scalar NULL, and sumIfState(x, NULL) now returns a real AggregateFunction(sumIf, ...) state instead of Nullable(Nothing). Please state which of these are intended and add tests for them.

Ignore this if the current title/body is intentional.

@clickgapai

Copy link
Copy Markdown
Contributor

Hi @amirreza1307 @Manerone — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Aug 13, 2026
This reverts merge f75ec00 (ClickHouse#112280) in
full, restoring all 15 files to their pre-merge content.

Besides adding `gini`, that pull request added nine
`getArgumentsThatCanBeOnlyNull` overrides across eight combinator files
and changed `-If`'s existing one to union the nested set, so a combinator
now forwards that set from the function it wraps. The `Null` combinator
uses the set to decide whether an argument that can only be NULL folds
the whole aggregate into `AggregateFunctionNothing`, so forwarding it
removed the fold one level up and changed the result type and value of
pre-existing expressions that chain one of those combinators on top of
`-If`. A combinator that gained no override keeps the empty set that
`IAggregateFunction::getArgumentsThatCanBeOnlyNull` returns by default,
so it contributes nothing of its own: `-Merge`, `-Array`, `-ForEach`,
`-Tuple` and `-Map` gained none, and
`sumIfForEach([number, number], [NULL, NULL])` still returns
`Array(UInt64)` `[0, 0]`.

Measured on debug builds of this branch and of its parent commit, which
contains the merge: `countIfOrNull(number, NULL)` moved from `UInt64` `0`
to `Nullable(UInt64)` `NULL`, `sumIfResample(0, 2, 1)(number, NULL,
number % 2)` from a scalar `Nullable(Nothing)` to `Array(UInt64)`
`[0, 0]`, and `sumIfState(number, NULL)` from a folded `Nothing` to a
real `AggregateFunction(sumIf, UInt64, Nullable(Nothing))` state. Those
two trees are equivalent to the merge and to its first parent on this
surface, by measurement rather than by assumption: for all 15 files the
merge touched, the blobs at the parent commit equal the blobs at the
merge, and the blobs at this branch's head equal the blobs at
f75ec00^1; no file under `src/AggregateFunctions/Combinators/`
differs between f75ec00^1 and this head; and of the 46 commits
between the merge and this branch's parent, the three that touch
`src/AggregateFunctions/` all belong to the unrelated PromQL `deriv`
scaling pull request 112360.

Four of the new overrides also insert their own column index, and the
two outside the `-If` family reach expressions with no `-If` at all,
such as `sumArgMin(1, NULL)`.

A partial revert is not available. `gini` declares argument 0 in
`getArgumentsThatCanBeOnlyNull` itself, and the same forwarding path
carries both that declaration and the `-If` filter index, so removing the
propagation while keeping `gini` would silently change `gini`'s own
combinator results and contradict assertions in its committed test.

`gini` is unreleased: the merge is not an ancestor of 26.7, 26.6, 26.5,
26.3 or 25.8, and it never reached `CHANGELOG.md`, so the revert returns
26.8-dev to its pre-merge state without withdrawing released behaviour.
A behaviour-neutral re-land of `gini` follows in a separate pull request.

Verified by byte identity rather than by a new test: all 15 files hash
equal to their `f75ec003a3ee^1` blobs, which is the whole correctness
criterion for a revert.

Closes: ClickHouse#113763
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-feature Pull request with new product feature 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.

7 participants