Skip to content

Preserve parameters in aggregate functions that dropped them, fixing the -Array combinator assert - #110143

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-groupArrayMovingSum-array-param-mismatch
Sep 4, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-groupArrayMovingSum-array-param-mismatch

Conversation

@groeneai

@groeneai groeneai commented Jul 12, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fixes a LOGICAL_ERROR (a server abort in debug and sanitizer builds) when the -Array combinator is applied with parameters to argMin, argMax, argAndMin, argAndMax, min_by, max_by, groupArrayMovingSum, groupArrayMovingAvg, kolmogorovSmirnovTest, mannWhitneyUTest or intervalLengthSum, for example argMaxArray(2)([1, 2, 3], [1, 2, 3]). These functions dropped the parameters they were given; they now preserve them, so a state type name also keeps them, e.g. AggregateFunction(groupArrayMovingSum(42), UInt64) instead of dropping the window size.

Description

Found by the AST fuzzer. Example abort:

Logical error: 'AggregateFunctionArray: parameters mismatch between Array wrapper 'groupArrayMovingSumArray' and nested function 'groupArrayMovingSum'. Wrapper has 1 parameter(s): [UInt64_42], nested function has 0 parameter(s): []'.

Reproducers, one per affected family:

SELECT groupArrayMovingSumArray(42)([1, 2, 3]);
SELECT argMaxArray(2)([1, 2, 3], [1, 2, 3]);
SELECT intervalLengthSumArray('two-sided', 1)([0., 1], [10., 3]);
SELECT mannWhitneyUTestArray('two-sided', 1)([1., 2, 3, 4], [0., 0, 1, 1]);

Root cause: each of these functions built its IAggregateFunctionDataHelper base with an empty parameter array instead of the parameters it was passed, so getParameters returned []. The -Array combinator does not transform parameters and asserts that the wrapper's parameters equal the nested function's; with the wrapper carrying [42] and the nested function returning [], the invariant fired. groupArrayMovingSum/groupArrayMovingAvg and kolmogorovSmirnovTest/mannWhitneyUTest are the set listed in the TODO added by #104812. intervalLengthSum and the argMin/argMax family instead accepted parameters and silently ignored them, so hard-rejecting them would make existing AggregateFunction(argMin(...), ...) metadata unreadable on upgrade; for those the parameters are preserved and normalized away in the state type via getNormalizedStateType, keeping legacy parameterless state columns Merge- and CAST-compatible.

No performance impact: the change only forwards an already-constructed parameter array to a base constructor, with no work added on any aggregation hot path.

Related: #104812


Workflow [PR]
Sync PR [sync-upstream/pr/110143]

…, mannWhitneyUTest

These aggregate functions accept parameters but constructed their base with an
empty parameter array, so getParameters() returned []. The -Array combinator
does not transform parameters and asserts wrapper.parameters == nested params,
so e.g. groupArrayMovingSumArray(42)([1,2,3]) aborted with a LOGICAL_ERROR.
Pass the parameters to the base constructor (the fix the ClickHouse#104812 TODO asked for).
Parameters are plain UInt64/String literals, so this does not reintroduce the
type-equality issue that reverted ClickHouse#103428.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT groupArrayMovingSumArray(42)([1,2,3]) aborts every time (RC 134) on a pristine debug build; also kolmogorovSmirnovTestArray('two-sided')(...) and mannWhitneyUTestArray('two-sided',1)(...).
b Root cause explained? These functions accept parameters but constructed their IAggregateFunctionDataHelper base with {}, so getParameters() returned []. The -Array combinator does not transform parameters and asserts wrapper.parameters == nested->getParameters(); wrapper [42] vs nested [] → LOGICAL_ERROR.
c Fix matches root cause? Yes. Pass the actual parameters to the base constructor so getParameters() matches the wrapper — the exact fix the #104812 TODO asked for. Not a symptom guard.
d Test intent preserved / new tests added? New regression test 04368_group_array_moving_array_combinator_parameter covering all four functions under -Array plus state-type-name checks. No existing test weakened.
e Both directions demonstrated? Fails without fix (RC 134 on pristine binary, Build ID 4db9b7b7), passes with fix ([1,3,6], Build ID e63992e3); reference matches.
f Fix is general across code paths? Yes. The identical bug existed in all four functions in the #104812 TODO list (groupArrayMovingSum, groupArrayMovingAvg, kolmogorovSmirnovTest, mannWhitneyUTest); all four are fixed, not just the one the fuzzer hit.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Covers window-size param (with/without), string and string+uint params, Decimal and numeric arguments, and the no-parameter form (still [] → still valid).
h Backward compatible? Yes. Parameters stored as-is (plain UInt64/String, no normalization), so no AggregateFunction type-equality break (the trap that reverted #103428). Verified old param-less state type names (e.g. AggregateFunction(groupArrayMovingSum, UInt64)) still parse. No setting/format change.
i Invariants and contracts preserved? Yes. Restores the factory invariant getParameters() == parameters for these functions; state serialization format unchanged; results unchanged (verified groupArrayMovingSum/Avg/mannWhitneyUTest still compute correctly).

Session id: cron:clickhouse-worker-slot-1:20260712-043600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar @rschu1ze — could you review this? It resolves the getParameters() TODO from #104812 for the four remaining functions (groupArrayMovingSum/Avg, kolmogorovSmirnovTest, mannWhitneyUTest): they dropped their parameters, so the -Array combinator's parameter-equality check aborted (e.g. groupArrayMovingSumArray(42)([1,2,3])). Passing the parameters to the base constructor fixes it and also keeps them in the state type name. Values stay as-is (UInt64/String, no normalization), so no type-equality regression like #103428.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2ac1a61]

Summary: ✅


AI Review

Summary

This PR preserves aggregate-function parameters for the affected families so the -Array combinator no longer trips the wrapper-vs-nested parameter invariant, and it normalizes state identity where the parameters do not affect serialized state so legacy AggregateFunction(...) columns remain Merge/CAST-compatible. I found no remaining correctness, compatibility, or coverage issue in the current diff after checking the added normalization against DataTypeAggregateFunction::equals, AggregateFunctionMerge, aggregate-to-aggregate CAST, and the updated stateless regression.

Missing context / blind spots
  • ⚠️ No local build artifacts were available in this checkout, so I did not execute 04368_group_array_moving_array_combinator_parameter and validated the new state-compatibility path statically against the implementation and expected test coverage instead.
Final Verdict

✅ No blocking issues found in the current diff.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 141/158 (89.24%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 12, 2026
The window-size / test parameters of groupArrayMovingSum, groupArrayMovingAvg,
kolmogorovSmirnovTest and mannWhitneyUTest only affect finalization, not the
serialized state. Now that the parameters are preserved, the state type name
carries them (e.g. AggregateFunction(groupArrayMovingSum(42), UInt64)), which
made the new parameterized state incompatible for -Merge and aggregate CAST
with legacy parameterless columns written before the change (state comparison
goes through getNormalizedStateType -> DataTypeAggregateFunction::equals, which
now saw a different parameter count).

Override getNormalizedStateType() to normalize to an empty parameter list, the
same approach quantile* uses for finalization-only parameters, so a legacy
parameterless state and a new parameterized state share one representation.
getParameters() still returns the parameters, so the -Array combinator
invariant continues to hold.

Extend the regression test to write a legacy parameterless state column and
Merge it with the parameterized function.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Good catch, the compatibility concern is real and now fixed in 468fa74.

The parameters here only affect finalization: serialize/deserialize in all four functions store just the accumulated values, and the window-size / test parameters are consumed only in insertResultInto / getResult. So the serialized state is identical whether or not the parameters are present, exactly the quantile* situation.

State comparison for -Merge and aggregate CAST goes through getNormalizedStateType() -> DataTypeAggregateFunction::equals -> strictEquals, which compares the parameter list. Since the new type carries [42] while a legacy column carries [], they stopped comparing equal. Fix: override getNormalizedStateType() in MovingImpl, AggregateFunctionKolmogorovSmirnov and AggregateFunctionMannWhitney to normalize to an empty parameter list (the same technique AggregateFunctionQuantile::getNormalizedStateType uses). getParameters() still returns the real parameters, so the -Array invariant continues to hold.

Verified against a build of the previous commit (parameter passing without normalization): groupArrayMovingSumMerge(2) over a legacy AggregateFunction(groupArrayMovingSum, UInt8) column failed with Code: 43 ... State types: 'AggregateFunction(groupArrayMovingSum(2), UInt8)' vs 'AggregateFunction(groupArrayMovingSum, UInt8)'; with the fix it returns the correct result. The regression test now writes a legacy parameterless column and Merges it with the parameterized function.

intervalLengthSum takes no parameters, but its factory silently dropped any
passed parameters. The -Array combinator then aborted on the wrapper-vs-nested
parameter mismatch (STID 4870-4f21, found by the AST fuzzer while exercising the
new 04368 test). Reject parameters with assertNoParameters instead.

The 04368 legacy-compatibility check asserted the exact merged array of two
concatenated states, whose order is not deterministic (and varies under parallel
replicas). Assert order-independent invariants (element count and running total)
instead.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 303071f addressing two CI failures on the previous head:

  1. AST fuzzer STID 4870-4f21 (intervalLengthSumArray('two-sided', 1)(...) LOGICAL_ERROR in the -Array combinator). Root cause is a pre-existing, separate bug: intervalLengthSum takes no parameters, but createAggregateFunctionIntervalLengthSum silently ignored a passed parameter Array, so the runtime function had 0 parameters while the -Array wrapper carried 2, tripping the same wrapper-vs-nested assert this PR targets. The fuzzer surfaced it because the new 04368 test seeds the ('two-sided', 1) parameter shape into the targeted corpus. Fixed by rejecting parameters via assertNoParameters (its params are non-semantic, unlike the four functions this PR preserves them for).

  2. Flaky 04368 (Stateless tests FAIL). The final legacy-compat query asserted the exact merged array of two concatenated states, whose concatenation order is not deterministic (and differs under parallel replicas). Now asserts order-independent invariants (element count = 6, running total = 66).

Validated: 04368 passes 60/60 with randomized settings; intervalLengthSum('two-sided', 1)(...) and its -Array form now return AGGREGATE_FUNCTION_DOESNT_ALLOW_PARAMETERS instead of aborting; parameterless intervalLengthSum(start, end) unchanged.

The window-size parameter of groupArrayMovingSum/Avg accepts both Int64 and
UInt64. After preserving parameters, the state type name printed the value
without a type suffix, so groupArrayMovingSumState(42::Int64) serialized as
AggregateFunction(groupArrayMovingSum(42), UInt64) and reparsed the parameter
as UInt64, breaking lossless round-trip of the type name through metadata.

Override shouldPrintParametersWithTypes() so a positive Int64 parameter stays
42::Int64 in the printed type name (same approach as AggregateFunctionTimeseriesBase).
The -Array invariant is unaffected: it compares parameter Field values, not names.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in 2916916. Chose option (b): MovingImpl now overrides shouldPrintParametersWithTypes() to return true (same approach as AggregateFunctionTimeseriesBase), so a positive Int64 window size prints as 42::Int64 in the type name and round-trips losslessly.

Option (a) — normalizing the accepted integer to UInt64 in the ctor — would re-break the -Array invariant: AggregateFunctionArray compares parameters != nested_func->getParameters() by Field value, so the wrapper's Int64 would then mismatch the nested function's normalized UInt64.

Verified:

  • toTypeName(groupArrayMovingSumState(42::Int64)(number)) -> AggregateFunction(groupArrayMovingSum(42::Int64), UInt64), which reparses to the same type (CREATE TABLE + Merge over that column works).
  • Bare groupArrayMovingSumState(42) still prints groupArrayMovingSum(42) (UInt64).
  • -Array crash fix intact for both bare and ::Int64 params; legacy parameterless getNormalizedStateType() compat unaffected.

Added the requested regression to 04368: toTypeName(groupArrayMovingSumState(42::Int64)(number)) and the Avg variant.

KS/MWU are unaffected — their parameters are String (and MWU's second is UInt64), which already round-trip.

argMin, argMax and their aliases (argAndMin, argAndMax, min_by, max_by)
take no parameters but createAggregateFunctionArgMinMax silently ignored
the passed Array, building the base with empty params. The -Array
combinator then aborted on the wrapper-vs-nested parameter mismatch
(AggregateFunctionArray LOGICAL_ERROR, e.g. argMinArray('two-sided', 2)).
Reject parameters up front via assertNoParameters, matching the
intervalLengthSum fix.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed ec7cea0. The AST fuzzer hit the same -Array param-mismatch abort in argMinArray('two-sided', 2)(...). Root cause is the same class as intervalLengthSum: createAggregateFunctionArgMinMax accepted a const Array & and silently dropped it, so the runtime function had 0 params while the -Array wrapper carried them.

To catch the whole family in one pass rather than per-fuzzer-finding, I runtime-probed all 236 aggregate functions with fnArray(params)(...): the only remaining crashers were the six that route through this one factory (argMin, argMax, argAndMin, argAndMax, min_by, max_by). None of them take semantic parameters, so the fix is assertNoParameters (not param preservation) — one line in the shared factory fixes all six. Bare/parameterless argMin/argMinArray are unchanged; parameterized forms now return AGGREGATE_FUNCTION_DOESNT_ALLOW_PARAMETERS instead of aborting.

Extended 04368 to cover the argMin/argMax family (both the clean rejection and the still-working parameterless path).

The compatibility block only proved the legacy-state upgrade path for
groupArrayMovingSum. kolmogorovSmirnovTest and mannWhitneyUTest get the same
getNormalizedStateType() normalization, so add one focused legacy-state case
each: write an old parameterless AggregateFunction(kolmogorovSmirnovTest, ...) /
AggregateFunction(mannWhitneyUTest, ...) column, then confirm it stays usable
via parameterized ...Merge(...) and accepts aggregate-to-aggregate inserts of
new parameterized states.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Extended 04368_group_array_moving_array_combinator_parameter with one focused legacy-state case for each family (commit a11c17a):

  • kolmogorovSmirnovTest: write an old parameterless AggregateFunction(kolmogorovSmirnovTest, Float64, Float64) column, then kolmogorovSmirnovTestMerge('two-sided') over it and an aggregate-to-aggregate insert of a new parameterized state, merging again.
  • mannWhitneyUTest: same, with the ('two-sided', 1) parameters.

Both assert order-independent invariants of the finalized result (d_statistic/u_statistic in range), so they stay deterministic under randomized merge order and are parallel-safe (unique test DB). Verified they fail before the getNormalizedStateType() overrides (same ILLEGAL_TYPE_OF_ARGUMENT the groupArrayMovingSum case shows) and pass after.

The previous fix rejected parameters in intervalLengthSum and the
argMin/argMax family with assertNoParameters to kill the -Array combinator
abort. But before this PR those factories silently ignored parameters, so
persisted types like AggregateFunction(intervalLengthSum('two-sided', 1), ...)
and AggregateFunction(argMin('x', 1), ...) exist in the wild. Hard-rejecting
them made that metadata unreadable on upgrade (reparsed via
AggregateFunctionFactory::get).

Preserve the parameters on the function object instead, so getParameters()
matches the -Array wrapper, and override getNormalizedStateType() to normalize
them to Array{} in the state type. The parameters are non-semantic here and
never touch the serialized state, so a parameterized state and a legacy
parameterless column share one representation and stay Merge-/CAST-compatible.
Same approach already used for groupArrayMovingSum/Avg, kolmogorovSmirnovTest
and mannWhitneyUTest in this PR.

Extend 04368 with legacy-state compatibility cases for intervalLengthSum and
argMin/argMax.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in 8295853. Both intervalLengthSum and the argMin/argMax family (incl. argAndMin/argAndMax/min_by/max_by) now preserve their parameters and override getNormalizedStateType() to normalize them to Array{}, matching the approach used for groupArrayMoving*/kolmogorovSmirnovTest/mannWhitneyUTest. The parameters are non-semantic and never enter the serialized state, so:

  • Legacy AggregateFunction(intervalLengthSum('two-sided', 1), ...) / AggregateFunction(argMin('x', 1), ...) metadata reparses cleanly (no more AGGREGATE_FUNCTION_DOESNT_ALLOW_PARAMETERS on upgrade).
  • A parameterized state and a legacy parameterless column share one normalized state type, so -Merge(...) and aggregate-to-aggregate CAST both keep working.
  • The -Array invariant still holds because getParameters() returns the real parameters.

Verified locally: legacy parameterless intervalLengthSum / argMin / argMax columns now -Merge(...) with the parameterized function and accept inserts of new parameterized states. 04368 extended with a legacy-state case per family and passes.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 8295853

Every failure below has an owner.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky #110030 (ours, open)

Session id: cron:our-pr-ci-monitor:20260712-183000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.60% +0.10%

Changed lines: Changed C/C++ lines covered: 139/158 (87.97%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 919af58

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_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky, trunk — under parallel replicas one statement becomes several reads of the same table on this server, each with a different query id, so the long-running holder query competes against itself for the single max_concurrent_queries slot and is rejected instead of holding it #112385 (ours, open)

The earlier partial fix #111528 (pin max_threads = 1 on the holder query) is present on this
head and does not cover the parallel-replicas route, so #112385 disables parallel replicas for
this test outright.

Session id: cron:our-pr-ci-monitor:20260729-103000

@groeneai groeneai changed the title Preserve parameters in groupArrayMovingSum/Avg, kolmogorovSmirnovTest, mannWhitneyUTest Preserve parameters in aggregate functions that dropped them, fixing the -Array combinator assert Jul 31, 2026
The comment blocks above shouldPrintParametersWithTypes and
getNormalizedStateType narrated how the parameters were dropped before and
which spellings used to be accepted. That history belongs in the commit log,
not at the call site, so each block now states only the property a reader
needs there: the parameters do not reach the serialized state, therefore
parameterized and parameterless states normalize to one representation and
stay Merge-/CAST-compatible.

No functional change.
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2ac1a6169 with master 4faa0468e (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 706.02 MiB 703.55 MiB -2.47 MiB (-0.35%)

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

9 object files changed (+1.02 MiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsArgMinArgMax… 15.47 MiB 16.21 MiB +757.75 KiB (+4.78%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArrayMov… 5.40 MiB 5.62 MiB +232.27 KiB (+4.20%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionIntervalLengt… 855.69 KiB 888.62 KiB +32.93 KiB (+3.85%)

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

11 translation units recompiled, 52 s compile time in total, 11 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +5.3 s (+11%) in total before that adjustment.

Job report

@alexey-milovidov alexey-milovidov 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.

Alright.

@alexey-milovidov alexey-milovidov self-assigned this Sep 4, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 4, 2026
Merged via the queue into ClickHouse:master with commit 8486fb9 Sep 4, 2026
179 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 4, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

Answered in #118006 (comment): the bare argMinState / intervalLengthSumState path with a Map parameter is a real regression from this PR, reproduced against a pre-merge and a post-merge debug build, and I am preparing a fix. The combinator paths in that report (argMinIfState, argMinOrNullState, argMinDistinctState, argMinForEachState, intervalLengthSumIfState) fail on the pre-merge binary too, so that half is pre-existing rather than caused here.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 8, 2026
`argMin`, `argMax` and `intervalLengthSum` accept parameters but never read them. ClickHouse#110143 started
preserving them in `getParameters()` (the -Array combinator requires the wrapper's parameters to
equal the nested function's), and this PR kept them out of the state type. The name that travels
with a state serialized into a `Field` is built separately, in
`ColumnAggregateFunction::getTypeString()`, straight from `getParameters()`, so it still spelled
them out and disagreed with the state type:

    CREATE TABLE t (s AggregateFunction(argMin, UInt8, UInt8)) ENGINE = Memory;
    INSERT INTO t VALUES (arrayReduce('argMinState(map(1, 2))', [1, 2], [1, 2]));
    -- Code: 43, Cannot insert field with type AggregateFunction(argMin([(1, 2)]), UInt8, UInt8)
    --           into column with type AggregateFunction(argMin, UInt8, UInt8)

    SELECT dynamicType(x) FROM VALUES('x Dynamic', (arrayReduce('argMinState(map(1, 2))', [1, 2], [1, 2])));
    -- Code: 36, Expected a literal or a CAST of a literal, got '[(1, 2)]'

A `Map` parameter renders as `[(1, 2)]`, which the `AggregateFunction` type parser rejects, so
every consumer that re-derives a type from that name fails: `ColumnAggregateFunction::insert`,
`convertFieldToType`, and `FieldToDataType` when `Dynamic`/`Variant` discovers the variant type.

State a single property instead of duplicating the parameter list: `areParametersPartOfState()`
replaces the two per-function `getStateType()`/`getNormalizedStateType()` overrides and also
decides what the column prints, so both carriers agree by construction. `getParameters()` keeps
returning the real parameters, so the -Array invariant is untouched.

Combinator-wrapped shapes (`argMinIfState`, `argMinArrayState`, ...) build their state type from
the wrapper's own parameters, fail the same way on master, and are unchanged here; they are
tracked in ClickHouse#118168.

A name that still spells those parameters (declared metadata, a binary encoded type, an older
server) denotes the same state, and `nameMatchesState` cannot recognise it because it starts by
parsing the name, so `acceptsStateTypeName` compares that spelling verbatim as well.
@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov, should this PR go to the release branches, together with #118156?

26.3, 26.7 and 26.8 do not have it. Measured on official builds:

  • 26.8.15.10: SELECT groupArrayMovingSumArray(2)([1, 2, 3]) fails with Code: 49 ... parameters mismatch ... (LOGICAL_ERROR), and the same error aborted the 26.8 Stress test (amd_asan_ubsan). The check throws in release builds since Replace chassert with diagnostic LOGICAL_ERROR in AggregateFunctionArray #102868 (mine), so 26.3.38.2 still returns [1,3,5].
  • 26.3.38.2 and 26.8.15.10: a state column with an inferred type drops the parameter, so the result changes after a restart. The mannWhitneyUTest alternative falls back to two-sided the same way.
CREATE TABLE t ENGINE = MergeTree ORDER BY tuple() AS SELECT groupArrayMovingSumState(2)(number) AS s FROM numbers(5);
SELECT finalizeAggregation(s) FROM t; -- [0,1,3,5,7], after a restart [0,1,3,6,10]

This PR alone brings #118006 along: 26.9.7.9, which has it, cannot load a table built from argMinState(map(1, 2))(number, number) after a restart. So it should only go after #118156 is merged, with the same label on both (26.9 needs #118156 either way).

Options: v26.3-must-backport, v26.8-must-backport, or no backport for this PR.

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-unknown PR origin: unclassified (legacy task) 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

Development

Successfully merging this pull request may close these issues.

5 participants