Skip to content

Re-land aggregate function gini in the sum family - #114643

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:reland-gini-in-sum-family-113763
Aug 21, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:reland-gini-in-sum-family-113763

Conversation

@groeneai

@groeneai groeneai commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • New Feature

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 from 0 (all values equal) towards 1 as inequality grows; for a sample of n values the maximum is (n - 1) / n. NaN values are skipped, while infinite and negative values are rejected. The function returns Float64 and consumes O(n) memory.

Description

Re-lands the gini function that #113868 reverted, following the option-2 spec @ Manerone gave in #113763 (comment). gini now registers and folds exactly like sum.

Relative to #112280 it drops the getArgumentsThatCanBeOnlyNull override, .returns_default_when_only_null = true, and the argument_type->onlyNull() branch in the creator, and touches no file under src/AggregateFunctions/Combinators/. The property was doing the work: it made AggregateFunctionFactory::getImpl skip its only-null guard and build a real gini over Nullable(Nothing), so gini(NULL) returned Float64 nan where every sum-family function folds to Nullable(Nothing). Without it the fold happens in the Null combinator first, which is why createAggregateFunctionSum has no equivalent.

It also drops getOwnNullAdapter, at @ Manerone's request in #114643 (comment). Keeping it left gini the only function in the family whose plain and wrapped forms disagreed on nullability: the Null combinator consults that hook only on the object it wraps directly, and for giniIf / giniDistinct that is AggregateFunctionIf / AggregateFunctionDistinct, whose own adapters win. So gini(x) stayed Float64 while giniIf(x, c) became Nullable(Float64). Dropping it gives parity on the runtime axis too: 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.

Validated against sum on the same binary: every literal-NULL and Nullable-column cell matches its sum counterpart, and non-nullable results are unchanged from #112280.

Docs: gini.mdx plus 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 the FunctionDocumentation block by ci/jobs/scripts/docs/autogenerate/autogenerate_docs.py (--check clean) 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. The pr-autogenerated-docs label 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]

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
@groeneai

Copy link
Copy Markdown
Collaborator Author
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.

# Finding Verdict
⚠️ gini is case-sensitive while sum is Case::Insensitive, so GINI does not resolve Disagree. Already the case in #112280 (registerFunction("gini", {..., properties}), no Case:: argument), so the three deletions did not introduce it. Only 10 of 159 registerFunction calls under src/AggregateFunctions are case-insensitive and all ten are SQL-standard or alias names; every statistics sibling registered in the same block (cramersV, theilsU, contingency, cramersVBiasCorrected) is case-sensitive. Adding the flag would be a fourth, unrequested change.
⚠️ The wide integer/decimal arms assert only gini(x) > 0, so a wrong-but-positive result passes Disagree. Those four statements are byte-identical to #112280, and they target one mutation: an early Float64 conversion that collapses adjacent wide values. Under it maximum equals every value, the pairwise sum is 0, and the result is exactly 0, which > 0 catches. The true values are 1.9e-37, 1.4e-73, 2.5e-31, 2.5e-61, far from any float noise floor. Exact-value oracles for the same mechanism already exist: 2^53 vs 2^53+1 as UInt64 asserts 2.7755575615628914e-17, and the BFloat16 pair asserts 1/514.
⚠️ 04891 invokes no gini and passes with this PR reverted, so it is dead Disagree. It is the pin requested in #113763 (comment) ("add the four repro queries from this issue to a stateless test so the <agg>If<Combinator>(x, NULL) behavior is pinned"), i.e. a regression test for behaviour #113868 restored, so passing on base is the intent. Master currently has no coverage of it: git grep over tests/ returns 0 files for countIfOrNull, uniqIfOrNull and sumIfResample, and the single sumIfState hit passes a real condition rather than NULL (control: sumIf matches 66 files).
💡 The documented 0.3666666666666665 differs from the returned 0.36666666666666664 Noted, not changed. Correct arithmetic: the result is 11/30. The string is byte-identical in #112280 and in the merged Mintlify port #114314, and all four docs paths here hash byte-for-byte to that commit, which is what makes this half a plain restoration. Changing it would exceed the three-deletion scope, so it is left for a follow-up if wanted.

Session id: cron:clickhouse-review-slot-8:20260813-124100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 04891_agg_if_combinator_null_fold fails deterministically on a build carrying #112280's version of the function, and its four cells are fixed-value, so no randomization is involved. Command: clickhouse-test --binary <pre-revert build> 04891_agg_if_combinator_null_fold.
b Root cause explained? Yes. .returns_default_when_only_null = true made AggregateFunctionFactory::getImpl skip its only-null guard, so the factory built a real gini instance over Nullable(Nothing) instead of returning nullptr. The same property also selected AggregateFunctionNothingUInt64 over AggregateFunctionNothingNull inside the Null combinator. Together with the getArgumentsThatCanBeOnlyNull override, that made gini(NULL) return Float64 nan where the sum family folds to Nullable(Nothing).
c Fix matches root cause? Yes. The three deletions remove gini's special case from the shared mechanism, which is @ Manerone's own line-level spec. No guard, no widened bound, no no-random-* tag, no test weakening. gini now registers exactly like sum.
d Test intent preserved / new tests added? Yes. Lines 1-63 and 66-69 of 04651_gini_aggregate.sql are unchanged; the literal-NULL block is rewritten to assert the new shape via isNull/toTypeName (never isNaN, which returns \N on a folded result and would assert nothing). The new 04891 test pins the four repro queries from the issue. The re-landed test shrank from 102 to 98 lines.
e Both directions demonstrated? Yes. 04651 and 04891 both FAIL on a build carrying #112280's version and PASS on this branch; 04891 also passes on the plain post-revert base. 00001_select_1 passed on every arm as an environment control. Each binary's ELF Build ID was asserted equal to SELECT lower(buildId()) before measuring.
f Fix is general across code paths? Yes. All nine combinator shapes were measured (If, State/Merge, OrNull, OrDefault, Resample, Distinct, ArgMin, ArgMax, and ArgMin(1, NULL)) and each equals the sum value on the same binary. createAggregateFunctionSum was read and has no only-null branch (grep -c onlyNull = 0), so no symmetric fix is owed. Zero files under src/AggregateFunctions/Combinators/ are touched, per the requested scope. The already_transformed guard is confirmed absent and was not re-added.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Nullable, all-NULL, literal NULL, (U)Int*, Float*, BFloat16, Decimal32/64/128/256, empty input, single-value input and the 1e308 / 2^120 / 2^240 boundary cases are all exercised by 04651 and all pass. The non-NULL reference rows are byte-identical to the previously merged file, so no input class regressed. aggregate_functions_null_for_empty = 1 was measured on both arms.
h Backward compatible? (maintainer-approved exception only) Yes, vacuously. gini is unreleased (the merge is not an ancestor of any active release branch) and #113868 already restored the combinator behaviour, so nothing users can have is withdrawn. No setting, no default, no serialization version: SettingsChangesHistory.cpp files touched = 0. No Backward Incompatible Change entry is required.
i Invariants and contracts preserved? Yes. No concurrency and no persistence are involved. The aggregate state format is byte-identical to #112280's (serialize/deserialize unchanged), so no versioning is owed. getOwnNullAdapter's contract is unchanged and its include retained; AggregateFunctionProperties now default-constructs to the same shape sum registers with. The creator's error paths are untouched apart from the removed only-null branch, which is unreachable once the factory guard fires.

Session id: cron:clickhouse-impl-slot-6:20260813-115600

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4a4672e]

Summary: ✅


AI Review

Summary

This PR re-lands the gini aggregate function with the intended NULL and Nullable behavior aligned to the surrounding aggregate/combinator machinery, restores the generated docs artifacts, and adds focused stateless coverage for the literal-NULL, Nullable, and empty-input paths. I did not find unresolved correctness, compatibility, or evidence gaps in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.10% 87.00% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 93/115 (80.87%) · Uncovered code

Full report · Diff report

@Manerone

Copy link
Copy Markdown
Contributor

@groeneai you are changing docs which will most likelly be auto generated: slug_map, redirects, and the changes inside {/*AUTOGENERATED_START*/} and {/*AUTOGENERATED_END*/}

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

You are right, and I dropped all four docs files in 47dcd5d.

Checked each against the repo's own tooling: gini.mdx has its whole body inside {/*AUTOGENERATED_START*/} / {/*AUTOGENERATED_END*/}, and it is the only one of the four that check_autogenerated_regions.py flags, which is what made Docs check (Mintlify) red on 92099cea. slug-map.csv, navigation.json and redirects.json are generated indexes. Nothing is hand-written outside a generated region, so there was nothing to keep.

Nothing under src/ or tests/ references those paths, so the function and both tests are byte-identical to the reviewed commit. The page body comes from the FunctionDocumentation block in AggregateFunctionGini.cpp, which this PR restores, so autogeneration can fill the page from source.

I also dropped the pr-autogenerated-docs request from the description, since it no longer applies.

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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4a4672e42 with master c9207f0ac (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.41 MiB 702.01 MiB -2.40 MiB (-0.34%)

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 ⚠️

4 object files changed (+1.15 MiB total), 1 added.

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.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Both addressed in f990386, tests only.

On the aggregate_functions_null_for_empty gap: agreed, and it was real. Three arms added for gini, giniIf and the giniState/giniMerge round trip. Measured individually against a pre-revert binary they return Float64 / 0 there and Nullable(Float64) / NULL here, matching sum's Nullable(UInt64) / NULL. I checked each arm on its own rather than through the test result, because an earlier expected-error arm aborts the file first and would have hidden a vacuous addition.

Chasing that also turned up a second path the property flip reaches, which neither of us had pinned: over a Nullable column giniIf and giniDistinct are now Nullable(Float64), and giniIf yields NULL instead of nan when no row qualifies. sumIf and avgIf over the same input are Nullable and yield NULL on a binary built without gini, so that is the sum-family shape rather than anything specific to this function. Three more arms pin it. Direct gini(x) over a Nullable column stays Float64 0.25, since getOwnNullAdapter is kept verbatim.

On the combinator comment: you are right that it overstated the claim, so I narrowed the wording rather than adding coverage. AggregateFunctionCombinatorArray::transformArguments does reject Nullable(Nothing), and giniArray, giniForEach and giniMap all raise ILLEGAL_TYPE_OF_ARGUMENT. That is not a gini property though: sumArray, sumForEach and sumMap raise the identical errors on a binary with no gini in it, so there is nothing for this PR to fix or pin there.

Both tests pass on this branch and redden on the pre-revert binary; 50 runs each with randomized settings, 100/100.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for f990386

CI is fully finished on this head: 177 checks, 0 incomplete, Finish Workflow and Config Workflow both green, 0 dropped jobs in the praktika report (result_pr.json top-level OK). No failed check and no failed test: CIDB has 534143 rows for this commit and zero rows with test_status IN ('FAIL','ERROR').

Nothing to own. CH Inc sync is pending as always and is not actionable by me.

Session id: cron:our-pr-ci-monitor:20260814-010000

@Manerone

Copy link
Copy Markdown
Contributor

@groeneai you removed the whole of gini.mdx, it should have a header that comes before {/*AUTOGENERATED_START*/}. Check reference/functions/aggregate-functions/any.mdx for an example.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Restored in 179ac64, following any.mdx: frontmatter, then the hand-written header, then {/*AUTOGENERATED_START*/}. All four paths are byte-identical to their merged state in #114314, which the revert had taken out as collateral.

The .mdx alone was not enough, so I brought back its three index entries too. Without the slug-map row build_file_map resolves no Mintlify destination and the nightly generator fails for this page with ValueError: no Mintlify destination for docs/sql-reference/aggregate-functions/reference/gini.md; with the row present it reports the page as up to date. And gini was the only one of 163 aggregate pages missing from navigation.json.

One thing I cannot do from here: a page carrying the markers cannot pass the generated-region guard, which asks for the pr-autogenerated-docs label. You applied that label to #113868 yourself. Could you add it here as well, or tell me if you would rather I ship the page without the markers?

@Manerone Manerone added the pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard label Aug 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 179ac64

CI is fully finished on this head: 177 leaves, 154 OK, 20 skipped (each with a reason),
0 dropped jobs, three failures. Every failure below has an owner.

Check / test Reason Owner / fixing PR
Docs check (Mintlify) / No direct edits to generated or read-only docs PR-caused, already resolved by the pr-autogenerated-docs label fixed in this PR, label applied at 11:36:40Z
AST fuzzer (amd_debug, targeted) / AggregateFunctionArray: parameters mismatch (STID 4870-4d8d) fuzzer-found trunk bug in the -Array combinator, not reachable from this diff #110143 (ours, open)
Stress test (amd_asan_ubsan) / Sizes of nested column and null map ... not equal after deserialization (STID 6726-6874) trunk bug in set skip-index deserialization #112484 (ours, open)

Docs check. The guard compared 179ac649 against the merge base and flagged
docs/reference/functions/aggregate-functions/gini.mdx, which 179ac649 restores with its
hand-written header. docs_job_mintlify.py:140-142 skips the generated-region guard when the PR
carries pr-autogenerated-docs, and @Manerone applied that label at 11:36:40Z. This run started at
11:24:34Z, so it predates the label and praktika does not re-run a completed job. The next run on a
new head will take the skip path. The read-only-copies half of the guard already passed
(OK: no edits to read-only copied docs).

STID 4870-4d8d. The fuzzed query is
SELECT DISTINCT id, groupArrayMovingSumArray(65535)(v) OVER (...), aborting in
AggregateFunctionArray.h:55 because the wrapper carries one parameter and the nested
groupArrayMovingSum reports none. #110143 preserves those parameters in
AggregateFunctionGroupArrayMoving.cpp and covers this exact call in
04368_group_array_moving_array_combinator_parameter. The family has 30 days of hits on unrelated
PRs and master.

STID 6726-6874. Aborts in SerializationNullable.cpp:178 under
MergeTreeIndexBulkGranulesSet::deserializeBinary, reading a set index granule whose on-disk type
is stale. 30-day breadth is 40+ hits across 25 unrelated PRs and master, none of it reachable from a
gini aggregate function.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b2d1216

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / Segmentation fault (STID 3361-3475) + Server died crash #109891 (external, open)
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) / Segmentation fault (STID 3718-37dd) + Server died crash #109891 (external, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Segmentation fault (STID 4105-1b04) + Server died crash #109891 (external, open)
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) / Segmentation fault (STID 4105-1b04) + Server died crash #109891 (external, open)
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 3/3) / Segmentation fault (STID 4105-1b04) + Server died crash #109891 (external, open)
Stateless tests (amd_tsan, s3 storage, parallel, 1/3) / ThreadSanitizer heap-use-after-free (STID 3361-4063) + Server died crash #109891 (external, open)
Stress test (arm_asan_ubsan, s3) / AddressSanitizer heap-buffer-overflow (STID 3361-3475) crash #109891 (external, open)

All five STIDs are one defect: a use-after-free of a borrowed ThreadGroup whose
memory_tracker / performance_counters point into a parent query group that has already
finished. Every stack bottoms out in MemoryTracker::setParent or
ProfileEvents::Counters::increment reached from
ThreadGroupSwitcher -> CallbackRunnerTask::run on a pool thread. #109891 rewrites exactly
those frames (ThreadGroupSwitcher.{h,cpp}, ThreadStatus.{h,cpp}, ThreadStatusExt.cpp,
threadPoolCallbackRunner.h).

Not caused by this PR: this diff adds one aggregate function plus docs and tests
(AggregateFunctionGini.cpp, registerAggregateFunctions.cpp, two .sql/.reference
pairs, docs) and touches no memory-tracking or thread-group code. Over 30 days these
signatures span 18 to 31 unrelated PRs each with 3 to 10 master hits, and all four
predate this head by weeks (earliest 2026-07-24).

Session id: cron:our-pr-ci-monitor:20260814-230000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7ddc07c

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 (arm_tidy) / Build ClickHouse inherited master build break - FAILED: .../gtest_merge_join_starved_totals.cpp.o, no matching function for call to '__construct_at' #115087 (mine, merged 2026-08-17T10:03:23Z) - not yet on this branch, see below
CH Inc sync - CH Inc sync (private, not actionable by me)

Not caused by this PR. The failing target is a unit test whose TableJoin construction went stale
against a master signature change; this PR's diff (AggregateFunctionGini.cpp,
registerAggregateFunctions.cpp, two test pairs, four docs files) greps 0 for that gtest, TableJoin
or JoinAnalyzeMode. The break hit master itself (9 master commits red between 06:31Z and 09:53Z) and
79 distinct PRs in the same window.

The fix is #115087, merged at 10:03Z. This head was built at 09:25Z, i.e. before it landed, so the fix
is not an ancestor of this branch and the red is expected here. Master's Build (arm_tidy) returned to
success from 10:00Z onward. No action is needed on this branch: the next run that picks up master will
build clean. I am not pushing a master merge, since the last commit here is a maintainer's own merge and
this check does not block the merge decision.

Session id: cron:our-pr-ci-monitor:20260817-170000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@Manerone
Manerone added this pull request to the merge queue Aug 20, 2026
@Manerone
Manerone removed this pull request from the merge queue due to a manual request Aug 20, 2026
@Manerone

Copy link
Copy Markdown
Contributor

1. Nullability of gini over a Nullable column now depends on the combinator

getOwnNullAdapter is only consulted on the function object the Null combinator wraps directly. For giniIf / giniDistinct that object is AggregateFunctionIf / AggregateFunctionDistinct, whose own adapters win and fall through to the generic path, where

return_type_is_nullable = !properties.returns_default_when_only_null && canBeInsideNullable()

(AggregateFunctionNull.cpp:128, AggregateFunctionIf.cpp:473). Dropping the property flipped that from false to true:

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 — the BFloat16 special-casing is dead weight. is_floating_point already includes BFloat16 (base/base/extended_types.h:68-70) and isNaN / isFinite already dispatch through DecomposedFloat<BFloat16> (base/base/DecomposedFloat.h:26). isNaNValue / isFiniteValue can be plain isNaN / isFinite, and || std::is_same_v<Value, BFloat16> at :160 can 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 at gini.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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

All five taken, in f7e3bcd and 43159d7.

1. Dropped the override. Confirmed your reading first: the Null combinator consults getOwnNullAdapter only on the object it wraps directly, so AggregateFunctionIf::getOwnNullAdapter (AggregateFunctionIf.cpp:465) wins for giniIf, and the generic path at AggregateFunctionNull.cpp:129 decides the rest. sum has no such override, so this is what parity actually requires. Measured against sum on one binary, over Nullable(Int32):

gini sum
[1, NULL, 3] Nullable(Float64) 0.25 Nullable(Int64) 4
giniIf(x, x > 1) / sumIf Nullable(Float64) nan Nullable(Int64) 3
giniDistinct / sumDistinct Nullable(Float64) 0.25 Nullable(Int64) 4
[NULL, NULL] Nullable(Float64) NULL Nullable(Int64) NULL
nothing qualifies (x > 100) Nullable(Float64) NULL Nullable(Int64) NULL

nan where exactly one value remains, NULL where none does, and non-nullable input is unchanged (Float64 for both plain and wrapped). This also made the AggregateFunctionNull.h include dead, so the file no longer references Combinators/ at all.

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-NULL and no-non-NULL cases split out.

3. Both say "infinite and negative values are rejected" now, in the description and the changelog entry.

Nits. Both done: isNaNValue / isFiniteValue are gone in favour of plain isNaN / isFinite and the is_same_v<Value, BFloat16> arm at :160 with them (BFloat16 results unchanged, still covered by the three BFloat16 cases in the test); trailing whitespace trimmed, so the generated page has no whitespace-only line.

The generated region is regenerated by ci/jobs/scripts/docs/autogenerate/autogenerate_docs.py, --check clean. While regenerating I noticed the skewed-distribution example printed 0.3666666666666665 against an actual 0.36666666666666664; corrected in 43159d7.

I also updated the PR description, which still said runtime Nullable handling was unchanged.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 43159d7

Every failure below has an owner: a fixing PR (ours 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_debug) / Logical error Equal values are not contiguous within the range assumed to be sorted (STID 2508-3b73) pre-existing trunk flaky #113242 (ours, open)

Not caused by this PR, established two ways. Breadth: measured on the assertion signature rather
than the STID, 104 rows across 91 distinct pull requests plus 4 true-master commits in 30 days
(the STID alone reports only 3 pull requests, because the fingerprint hashes the query shape over
one fixed abort site). Timeline: the signature first fired 2026-07-26, while the first CI row for
this pull request is 2026-08-13, so it predates the branch. The diff here is gini plus docs and
tests, with no overlap on the aborting path.

Owner detail. The aborting query is
SELECT count() FROM (SELECT DISTINCT s FROM merge_distinct__fuzz_4 ORDER BY s ASC NULLS FIRST LIMIT 100)
with optimize_distinct_in_order = 1, taken from fatal.log together with its
log_comment = 04870_distinct_merge_over_distributed.sql. That is the fuzzer retyping the Merge
fixture's s column, here to Nullable(UInt256) (visible in the stack as ColumnNullable over
ColumnVector<wide::integer<256>>), and the frame chain matches the family exactly:
DistinctSortedStreamTransform.cpp:184 into findEqualRangeEndAssumeSorted.h:86. #113242 returns
FetchColumns when conversionPreservesOrder(child, declared) is false in
StorageMerge::getQueryProcessingStage, which stops the order-breaking cast being applied above a
child's own sort. That is the mechanism this abort needs, verified from its diff rather than its
title. It is open, so it was never present in this build.

The other 9 Stress legs at this head are green, and the arm_debug job's remaining markers
(Test script exit code, Server successfully started, No lost s3 keys,
No SharedMergeTree lost forever) all report OK, so this is one event with one owner.

No push, rebase or master merge was made: the head commit is a third party's, and the check is
not gating for the merge decision.

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

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 21, 2026
Merged via the queue into ClickHouse:master with commit b93eea1 Aug 21, 2026
177 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard 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.

4 participants