Skip to content

Aggregate function combinator -Tuple - #98190

Merged
nihalzp merged 75 commits into
ClickHouse:masterfrom
RinChanNOWWW:tuple-combinator
Jul 8, 2026
Merged

nihalzp merged 75 commits into
ClickHouse:masterfrom
RinChanNOWWW:tuple-combinator

Conversation

@RinChanNOWWW

@RinChanNOWWW RinChanNOWWW commented Feb 27, 2026 •

Copy link
Copy Markdown
Contributor

Closes #98011

Changelog category (leave one):

  • New Feature

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

Add aggregate function combinator -Tuple, which applies the underlying aggregate function to each element of a Tuple column independently and returns a Tuple of the results, preserving element names: sumTuple(t) for t = (a, b) returns (sum(a), sum(b)). Aggregate functions with several arguments take one tuple per argument, paired by position: corrTuple((a1, a2), (b1, b2)) returns (corr(a1, b1), corr(a2, b2)). Unlike -ForEach over arrays, elements may have different types, and per-element result types and names are preserved.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.648 (included in 26.7 and later)

@nihalzp nihalzp added the can be tested Allows running workflows for external contributors label Feb 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Feb 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [272d6b9]

Summary: ✅


AI Review

Summary

This PR adds the -Tuple aggregate combinator, resolves one nested aggregate per tuple element, and extends it across multi-argument aggregates, sparse tuple inputs, state normalization, cross-variant merge, and parallel merge. I reviewed the current code and prior discussion and did not find a remaining correctness, compatibility, or test-contract issue in the current head.

Missing context / blind spots
  • ⚠️ I could not rerun the suite locally because this checkout does not include a build directory or clickhouse binary, and the CI helper could not fetch the latest report with the current GitHub token policy. The review is based on the current code, added tests, and the existing PR discussion.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Feb 27, 2026
@RinChanNOWWW

Copy link
Copy Markdown
Contributor Author

PTAL @alexey-milovidov @nihalzp

@nihalzp nihalzp self-assigned this Mar 3, 2026

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

❌ serialize/deserialize in AggregateFunctionTuple currently ignore the incoming version and effectively force nested functions to use std::nullopt (current default format).

This breaks versioned aggregate-state compatibility during rolling upgrades: ...State produced for an older revision can be serialized/deserialized with a mismatched nested format.

Please pass the received version through to nested calls in both methods, similar to other combinators (for example -Array / -ForEach).

@nihalzp nihalzp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good! Thanks for working on this. I have left a few comments.

Additionally, let's add test for the following cases:

Nullable tuple elements, parametric aggregate function (e.g. quantileTuple(0.5)(t)), multiple nested combinators (e.g. sumTupleDistinctIf), multi argument base function.

@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

@nihalzp I investigated the CI failures. Summary: none are caused by this PR. -Tuple only touches src/AggregateFunctions/Combinators/, AggregateFunctionFactory, ColumnSparse.h and tests; every failure below is a pre-existing chronic/randomization issue that reproduces across many unrelated PRs (verified via CIDB, 30-day cross-PR spread), and several also hit master.

Per-failure attribution (head 7af0692, before today's re-run):

Check Signature Cross-PR spread (30d) Attribution
AST fuzzer (amd_debug) KeyCondition uses PREWHERE output (STID 4419-44a9) 15 hits / 8 PRs / 0 master Known fuzzer-internal-path issue, tracked in #107951
Stress test (arm_tsan) Block structure mismatch ... different number of columns (STID 0993-308a) 55 hits / 46 PRs / 6 master Tracked in #109215
Stress test (arm_msan) Arguments of A have incorrect data types (STID 2735-474b) 5 hits / 5 PRs / 0 master Pre-existing MSan stress signature, unrelated to this PR
Stress test (amd_msan) Not-ready Set is passed as the second argument (STID 0250-41a5) 133 hits / 107 PRs / 18 master Tracked in #107619
Stateless (various) 03532_window_function_and_null_source_max_threads 80 hits / 48 PRs / 6 master Flaky, tracked in #109503. CI's own diagnosis: reproducible only with randomized setting query_plan_optimize_join_order_randomize, passes 157/157 without randomization
Upgrade check (amd_release) Error message in clickhouse-server.log 179 hits / 158 PRs / 0 master Generic chronic upgrade-check noise

CI report (example, AST fuzzer): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98190&sha=7af0692e1f4dd366b8215a0ca918c27a7a5d0ea5&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

The earlier Style check (cpp) and Build (arm_tidy) failures are now green. CI is currently re-running at the latest head (272d6b9); the checks above are expected to be flaky again but are not blockers introduced by this PR. Rebasing on latest master is recommended to pick up the merged fixes for the tracked issues.

@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.70% 85.70% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 77.90% +0.00%

Changed lines: Changed C/C++ lines covered: 402/442 (90.95%) · Uncovered code

Full report · Diff report

@nihalzp
nihalzp added this pull request to the merge queue Jul 8, 2026
Merged via the queue into ClickHouse:master with commit 1a42340 Jul 8, 2026
342 of 345 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 8, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…, parametric `-Merge`

Address reviewer feedback on PR ClickHouse#98190 from @nihalzp 2026-04-23:

1. `sumTuple(x)` on `Tuple(Int64, Float64)` column stored with
   `ratio_of_defaults_for_sparse_serialization` < 1 would crash with
   `Bad cast from type DB::ColumnSparse to DB::ColumnVector<long>`.
   MergeTree may keep individual Tuple-element streams as `ColumnSparse`
   while the outer `ColumnTuple` is dense, so nested aggregate functions
   would receive sparse columns they can't `assert_cast`. Override
   `addBatch`/`addBatchSinglePlace`/`addManyDefaults` (and add a defensive
   fallback inside `add`) to call `recursiveRemoveSparse` once per batch.

2. `sumTuple(tuple(NULL, toInt64(1)))` returned `(NULL,NULL)` of type
   `Tuple(Nullable(Nothing), Nullable(Nothing))` instead of `(NULL,1)` of
   type `Tuple(Nullable(Nothing), Int64)`. `transformArguments` was
   returning `elem_types[0]`, so when the first element was `Nullable(Nothing)`
   the recursive `get()` collapsed the representative function to
   `AggregateFunctionNothing*` and its name (`nothingNull`) became the base
   name used for every per-element nested function. Pick the first
   non-`onlyNull` element as the representative instead.

3. `quantilesTDigestTupleMerge(0.9)(quantilesTDigestTupleState(0.5)(...))`
   threw `ILLEGAL_TYPE_OF_ARGUMENT` because the default
   `haveSameStateRepresentationImpl` compares full state types, which
   include `AggregateFunctionTuple`'s own parameters (`0.5` vs `0.9`).
   Override `haveSameStateRepresentationImpl` to delegate to the nested
   functions pairwise, mirroring how `quantilesTDigest` already ignores
   parameters that affect only finalization.

Add regression tests for all three cases in `04003_tuple_combinator`.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Previously the batch overrides materialized the outer `ColumnTuple` once
via `recursiveRemoveSparse`, but then delegated to
`IAggregateFunctionHelper::addBatch`, which loops and calls `add` per
row. `add` itself calls `recursiveRemoveSparse(columns[0]->getPtr())`,
and `recursiveRemoveSparse` always builds a new `ColumnTuple` (it
unconditionally reassembles the elements), so we still paid a per-row
allocation in the hot aggregation loop. That regresses the main path
for `-Tuple` aggregation, not just sparse corner cases, and contradicts
the comment in the code claiming the batch paths materialize once.

Split out a `addRowFromMaterialized` helper that takes an already
materialized `ColumnTuple`, and call it directly from the row loop in
`addBatch`/`addBatchSinglePlace`. The fallback `add` still materializes
defensively for callers that bypass the batch overrides.

Addresses review thread `PRRT_kwDOA5dJV86DdTyt` on PR ClickHouse#98190.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…eType`

`getNormalizedStateType` bound a reference to `*nested_functions.front()->getNormalizedStateType()`,
but that nested call returns a freshly allocated `DataTypePtr` that owns the only reference to the
`DataTypeAggregateFunction`. Binding a reference to the pointee does not extend the temporary's
lifetime, so the object was destroyed at the end of the statement and the subsequent
`getParameters` call read freed memory while copying the parameters `Array`
(`std::vector<Field>`), as reported by AddressSanitizer in the flaky check.

Hold the nested normalized state type in a named local variable so it stays alive until the
parameters are copied.

CI report: ClickHouse#98190
ASan: heap-use-after-free in std::vector<DB::Field>::vector(const&) via
DataTypeAggregateFunction::getParameters -> AggregateFunctionTuple::getNormalizedStateType
(STID 1388-406d, flaky check amd_asan_ubsan)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 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 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.

Aggregate function combinator -Tuple

5 participants