Repository navigation
Re-land aggregate function gini in the sum family - #114643
alexey-milovidov merged 10 commits into
Conversation
Re-lands the gini aggregate function that was reverted in ClickHouse#113868, with the three changes @Manerone specified in issue ClickHouse#113763: no getArgumentsThatCanBeOnlyNull override, no returns_default_when_only_null property, and no argument_type->onlyNull() branch in the creator. The property was what made the factory build a real gini instance over Nullable(Nothing) instead of letting AggregateFunctionFactory::getImpl return nullptr, so gini(NULL) produced Float64 nan where every sum-family function folds to Nullable(Nothing). Without the property the fold happens in the Null combinator before any other combinator is applied, and the creator's only-null branch becomes unreachable, which is why createAggregateFunctionSum has no equivalent. Runtime Nullable handling is a separate axis via getOwnNullAdapter and is unchanged: gini over [1, NULL, 3] still returns 0.25. The docs artifacts restore what ClickHouse#113868's wholesale revert removed from @Blargian's merged Mintlify port (ClickHouse#114314): the gini.mdx page plus its slug-map, navigation and redirect entries, taken verbatim from that commit. Reported-by: Manerone
Internal second-model review (click to expand)A second model reviewed this diff cold. Four findings, all adjudicated against the source; none changed the code. Recorded here for transparency.
Session id: cron:clickhouse-review-slot-8:20260813-124100 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260813-115600 |
|
Workflow [PR], commit [4a4672e] Summary: ✅
AI ReviewSummaryThis PR re-lands the Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 93/115 (80.87%) · Uncovered code |
|
@groeneai you are changing docs which will most likelly be auto generated: slug_map, redirects, and the changes inside |
Manerone pointed out that the documentation changes here land in generated
output. Measured against the repo's own tooling, all four are:
- docs/reference/functions/aggregate-functions/gini.mdx: the whole body sits
between {/*AUTOGENERATED_START*/} and {/*AUTOGENERATED_END*/}, so
ci/jobs/scripts/docs/check_autogenerated_regions.py rejects it (it is the
only one of the four that the guard flags, and it is why Docs check
(Mintlify) was red on 92099ce).
- docs/_migration/slug-map.csv, docs/reference/navigation.json,
docs/_site/redirects.json: generated indexes, regenerated by the docs
tooling rather than hand-maintained.
The source of truth for the page body is the FunctionDocumentation block in
AggregateFunctionGini.cpp, which this PR restores. The nightly autogeneration
workflow reads it through system.functions and fills the page.
This leaves the three deletions from the issue's spec plus the two stateless
tests. Nothing under src/ or tests/ references the docs paths.
|
You are right, and I dropped all four docs files in 47dcd5d. Checked each against the repo's own tooling: Nothing under I also dropped the |
Three review findings on 04651_gini_aggregate.sql, tests only. Dropping returns_default_when_only_null also makes QueryAnalyzer.cpp:1096 append -OrNull to gini* under aggregate_functions_null_for_empty = 1, the same rewrite sum* gets. Measured on the pre-revert binary the three new arms return Float64/0 and on this branch Nullable(Float64)/NULL, matching sum's Nullable(UInt64)/NULL. Each arm was checked individually against the pre-revert binary rather than through the test-level result, because an earlier expected-error arm aborts the file first. The property also reaches the runtime-Nullable axis through the generic wrappers: over a Nullable column giniIf and giniDistinct are now Nullable(Float64), and giniIf yields NULL rather than nan when no row qualifies. sumIf and avgIf over the same input are Nullable and yield NULL on a binary built without gini, so this is the sum-family shape, not a gini-specific change. Direct gini(x) over a Nullable column stays Float64 0.25 because getOwnNullAdapter is kept verbatim. The combinator comment claimed every combinator sees the fold. Type-transforming combinators reject Nullable(Nothing) in transformArguments before the base aggregate resolves, and sumArray, sumForEach and sumMap raise the identical errors on a binary without gini, so the claim was the wording, not the code.
Build profile diff (arm_release)Comparing Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGini.cpp.o |
new | 1.15 MiB | +1.15 MiB |
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.
Compile time of recompiled translation units
8 translation units recompiled, 10 s compile time in total, 8 of them have a recent master baseline.
|
Both addressed in f990386, tests only. On the Chasing that also turned up a second path the property flip reaches, which neither of us had pinned: over a On the combinator comment: you are right that it overstated the claim, so I narrowed the wording rather than adding coverage. Both tests pass on this branch and redden on the pre-revert binary; 50 runs each with randomized settings, 100/100. |
CI finish ledger for f990386CI is fully finished on this head: 177 checks, 0 incomplete, Nothing to own. Session id: cron:our-pr-ci-monitor:20260814-010000 |
|
@groeneai you removed the whole of gini.mdx, it should have a header that comes before |
Manerone asked for gini.mdx to keep a hand-written header above the
{/*AUTOGENERATED_START*/} marker, patterned on any.mdx. All four paths are
restored byte-identically to their merged state in ClickHouse#114314, which the previous
revert had removed as collateral.
The .mdx alone is not sufficient: without the slug-map row build_file_map
resolves no Mintlify destination and the nightly generator raises
ValueError: no Mintlify destination for
docs/sql-reference/aggregate-functions/reference/gini.md. With the row present
the generator reports the page as up to date, and gini would otherwise be the
only one of 163 aggregate pages absent from navigation.json.
A page carrying the markers cannot pass the generated-region guard without the
pr-autogenerated-docs label, which is what the guard's own message asks for.
|
Restored in The One thing I cannot do from here: a page carrying the markers cannot pass the generated-region guard, which asks for the |
CI finish ledger - 179ac64CI is fully finished on this head: 177 leaves, 154
Docs check. The guard compared STID 4870-4d8d. The fuzzed query is STID 6726-6874. Aborts in Session id: cron:our-pr-ci-monitor:20260814-163000 |
The Docs check (Mintlify) run at 179ac64 was triggered before the pr-autogenerated-docs label was applied, and praktika snapshots PR_LABELS from the triggering event payload, so the generated-region guard ran without the label and reported the gini.mdx page as a direct edit. No content change is required: this merge produces a new head so the labels are re-read.
CI finish ledger - b2d1216Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
All five STIDs are one defect: a use-after-free of a borrowed Not caused by this PR: this diff adds one aggregate function plus docs and tests Session id: cron:our-pr-ci-monitor:20260814-230000 |
CI finish ledger - 7ddc07cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this PR. The failing target is a unit test whose The fix is #115087, merged at 10:03Z. This head was built at 09:25Z, i.e. before it landed, so the fix Session id: cron:our-pr-ci-monitor:20260817-170000 |
1. Nullability of
|
over Nullable(Int32) |
before (#112280) | this PR |
|---|---|---|
gini(x) |
Float64, nan |
Float64, nan |
giniIf(x, c) |
Float64, nan |
Nullable(Float64), NULL |
giniDistinct(x) |
Float64, nan |
Nullable(Float64), NULL |
Those rows agreed before and disagree now. gini becomes the only function in the family whose plain form is non-nullable while its combinator forms are nullable. The spec deliberately left the runtime-Nullable axis alone, but this asymmetry is on the runtime axis — it is a side effect of the fold change, not a choice the spec made.
Preferred fix is to drop the override too, which gives full sum parity on both axes (gini(nullable_col) → Nullable(Float64); NULL only when there is no non-NULL value, nan when there is exactly one):
- AggregateFunctionPtr getOwnNullAdapter(
- const AggregateFunctionPtr & nested_function,
- const DataTypes & arguments,
- const Array & params,
- const AggregateFunctionProperties &) const override
- {
- return std::make_shared<AggregateFunctionNullUnary<false, true>>(nested_function, arguments, params);
- }
-If the asymmetry is intended instead, please state it in the FunctionDocumentation description — nothing currently tells a user why gini(x) is Float64 but giniIf(x, 1) is Nullable(Float64).
2. Misleading test comment
tests/queries/0_stateless/04651_gini_aggregate.sql:71:
-- Over a Nullable column a wrapped gini is Nullable and yields NULL when nothing qualifies, as sumIf is.True of giniIf in isolation, but it reads as a parity claim. sumIf is Nullable because sum is; gini is not. Please reword so the test does not present the asymmetry as sameness.
3. Negative values are rejected, and nothing says so
AggregateFunctionGini.cpp:96 throws BAD_ARGUMENTS on a negative input, but the description (:262) and the argument text (:266) only say "non-negative", which reads as a precondition rather than a runtime error — while NaN and infinities are called out explicitly. Suggest extending the sentence to "… NaN values are skipped, while infinite and negative values are rejected." in both the description and the changelog entry.
Nits (non-blocking)
AggregateFunctionGini.cpp:61-75, 160— theBFloat16special-casing is dead weight.is_floating_pointalready includesBFloat16(base/base/extended_types.h:68-70) andisNaN/isFinitealready dispatch throughDecomposedFloat<BFloat16>(base/base/DecomposedFloat.h:26).isNaNValue/isFiniteValuecan be plainisNaN/isFinite, and|| std::is_same_v<Value, BFloat16>at:160can go.AggregateFunctionGini.cpp:262-263— the description raw string ends with a newline plus four spaces, which the generator reproduces as a whitespace-only line atgini.mdx:53. Trimming it in the source keeps the regenerated page clean.
Dropping `getArgumentsThatCanBeOnlyNull` fixed the literal-NULL fold but left `getOwnNullAdapter` in place, and the Null combinator only consults that hook on the function object it wraps directly. For `giniIf` / `giniDistinct` that object is `AggregateFunctionIf` / `AggregateFunctionDistinct`, whose own adapters win, so those forms became `Nullable(Float64)` while plain `gini` stayed `Float64`: `gini` was the only function in the family whose plain and wrapped forms disagreed on nullability. Drop the override as well. `gini` now matches `sum` on both axes: over a `Nullable` column every form returns `Nullable(Float64)`, `NULL` when no non-NULL value qualifies and `NaN` when fewer than two do. Non-nullable input is unchanged. Also, per review: reword the Nullable test section, which read as a parity claim it did not yet hold; say in the description that negative values are rejected rather than only that the input is non-negative; drop the `BFloat16` special-casing, since `is_floating_point` covers `BFloat16` and `isNaN` / `isFinite` already dispatch through `DecomposedFloat<BFloat16>`; and trim the trailing whitespace the description raw string reproduced in the generated page. Removing the override also makes the `AggregateFunctionNull.h` include dead.
The documented result was one digit short of what the function returns (0.3666666666666665 vs 0.36666666666666664), so the example did not match the query beside it. Regenerate the page from the corrected source.
|
All five taken, in 1. Dropped the override. Confirmed your reading first: the
2. Reworded. The section now asserts the parity rather than claiming it: plain and wrapped forms are checked side by side, with the one-non- 3. Both say "infinite and negative values are rejected" now, in the description and the changelog entry. Nits. Both done: The generated region is regenerated by I also updated the PR description, which still said runtime |
CI finish ledger - 43159d7Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Not caused by this PR, established two ways. Breadth: measured on the assertion signature rather Owner detail. The aborting query is The other 9 Stress legs at this head are green, and the arm_debug job's remaining markers No push, rebase or master merge was made: the head commit is a third party's, and the check is Session id: cron:our-pr-ci-monitor:20260820-200000 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
New aggregate function
gini, which calculates the Gini coefficient of a column of finite, non-negative numeric values. The result ranges from0(all values equal) towards1as inequality grows; for a sample ofnvalues the maximum is(n - 1) / n.NaNvalues are skipped, while infinite and negative values are rejected. The function returnsFloat64and consumesO(n)memory.Description
Re-lands the
ginifunction that #113868 reverted, following the option-2 spec @ Manerone gave in #113763 (comment).gininow registers and folds exactly likesum.Relative to #112280 it drops the
getArgumentsThatCanBeOnlyNulloverride,.returns_default_when_only_null = true, and theargument_type->onlyNull()branch in the creator, and touches no file undersrc/AggregateFunctions/Combinators/. The property was doing the work: it madeAggregateFunctionFactory::getImplskip its only-null guard and build a realginioverNullable(Nothing), sogini(NULL)returnedFloat64nanwhere everysum-family function folds toNullable(Nothing). Without it the fold happens in theNullcombinator first, which is whycreateAggregateFunctionSumhas no equivalent.It also drops
getOwnNullAdapter, at @ Manerone's request in #114643 (comment). Keeping it leftginithe only function in the family whose plain and wrapped forms disagreed on nullability: theNullcombinator consults that hook only on the object it wraps directly, and forginiIf/giniDistinctthat isAggregateFunctionIf/AggregateFunctionDistinct, whose own adapters win. Sogini(x)stayedFloat64whileginiIf(x, c)becameNullable(Float64). Dropping it gives parity on the runtime axis too: over aNullablecolumn every form returnsNullable(Float64),NULLwhen no non-NULLvalue qualifies andnanwhen fewer than two do. Non-nullable input is unchanged.Validated against
sumon the same binary: every literal-NULLandNullable-column cell matches itssumcounterpart, and non-nullable results are unchanged from #112280.Docs:
gini.mdxplus its slug-map, navigation and redirect entries are restored from their merged state in #114314, which #113868's revert had removed as collateral; the generated region is regenerated from theFunctionDocumentationblock byci/jobs/scripts/docs/autogenerate/autogenerate_docs.py(--checkclean) and the page keeps its hand-written header. The slug-map row is needed, not cosmetic: without it the nightly generator resolves no Mintlify destination and fails for this page. Thepr-autogenerated-docslabel is what lets a page carrying the markers pass the generated-region guard, as the guard's own message asks for.cc @Manerone
Workflow [PR]
Sync PR [sync-upstream/pr/114643]