Skip to content

Fix LOGICAL_ERROR in AggregateFunctionArray for timeSeries*ToGrid family - #104769

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-aggregate-function-array-timeseries-104459
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-aggregate-function-array-timeseries-104459

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

AggregateFunctionArray is an adapter combinator: agg(x) -> aggArray(x). It does not transform parameters, so its parameters should always be identical to the nested function's. For the vast majority of aggregate functions this is trivially true.

The timeSeries*ToGrid aggregate function family (AggregateFunctionTimeseriesBase) is the exception: it deliberately normalizes its four timestamp parameters to DecimalField<Decimal64> so that states serialized with different timestamp scales remain merge-compatible. With user-typed literals (e.g. UInt64_60) the wrapper's parameters did not match the nested function's normalized parameters (Decimal64_'60'), and the wrapper's equality check fired:

Logical error: 'AggregateFunctionArray: parameters mismatch between Array wrapper
'timeSeriesDeltaToGridArray' and nested function 'timeSeriesDeltaToGrid'.
Wrapper has 4 parameter(s): [UInt64_..., ...],
nested function has 4 parameter(s): [Decimal64_'...', ...]'

In CI debug / sanitizer builds (abort_on_logical_error: true) this surfaces as a server abort. The AST fuzzer hit it daily on master across many PRs (STID 4870-4f07 / 4f21 family, ~149 occurrences over 30 days).

A previous attempt to resolve this by dropping the normalization on the timeSeries*ToGrid side (#103428) was reverted in #104672 because it broke backward compatibility with already-serialized timeseries state columns whose metadata records Decimal64-normalized parameters. That path is not viable.

This PR fixes the issue on the wrapper side without touching the timeseries normalization. AggregateFunctionArray now forwards nested_->getParameters() to its IAggregateFunctionHelper base, which is a no-op for every aggregate function that does not normalize its own parameters, and produces consistent metadata for the timeseries family. The downstream equality check becomes always-true and is removed. The wrapper's runtime behaviour (add / merge / serialize / insertResultInto) is entirely delegated to the nested function and is unaffected.

Verified locally on the debug build:

  • the issue's reproducer (timeSeriesDeltaToGridArray(...), every 4-arg variant, and the 5-arg timeSeriesPredictLinearToGridArray) used to abort the server; with the patch they return the expected grid arrays.
  • INSERT-State / Merge / DETACH+ATTACH round-trip through an AggregateFunction(timeSeriesLastToGridArray(60, 180, 10, 20), ...) column preserves the data on disk and after re-attach.
  • existing Array-combinator tests (01441_array_combinator, 01570_aggregator_combinator_simple_state, 00915_simple_aggregate_function, 01129_state_array_unique) all pass — the change is a no-op for them.
  • new regression test 04235_timeseries_array_combinator_params_104459 passes 50 / 50 with --test-runs 50 under full randomization.

Reproducer:

SET allow_experimental_time_series_aggregate_functions = 1;
WITH CAST('[(1600000000, 10), (1600000010, 20), (1600000020, 30)]',
          'Array(Tuple(UInt32, Float64))') AS data
SELECT timeSeriesDeltaToGridArray(1600000010, 1600000320, 10, 300)(data.1, data.2);

CI report (AST fuzzer, amd_debug, targeted) on PR #104299, requested by @alexey-milovidov:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104299&sha=4c8770c47ae00af15728dff17dddd34f921076bd&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Fixes #104459.

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

Fix Logical error: AggregateFunctionArray: parameters mismatch when the Array combinator is applied to a timeSeries*ToGrid aggregate function (e.g. timeSeriesDeltaToGridArray, timeSeriesPredictLinearToGridArray, timeSeriesRateToGridArray). The timeSeries*ToGrid family normalizes its timestamp parameters to Decimal64 internally, which did not match the user-supplied parameters stored on the Array wrapper. The wrapper now inherits the nested function's parameters so the two always agree. This is a no-op for every other aggregate function.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

`AggregateFunctionArray` is an adapter combinator: `agg(x) -> aggArray(x)`. It
does not transform parameters, so its `parameters` should always be identical to
the nested function's. For the vast majority of aggregate functions this is
trivially true, because the factory hands the same parameter array to both the
nested function and the combinator wrapper.

The `timeSeries*ToGrid` aggregate function family (`AggregateFunctionTimeseriesBase`)
is the exception: it deliberately normalizes its four timestamp parameters to
`DecimalField<Decimal64>` so that states serialized with different timestamp
scales remain merge-compatible. With user-typed literals (e.g. `UInt64_60`) the
wrapper's parameters would not match the nested function's normalized parameters
(`Decimal64_'60'`), and the wrapper's equality check fired:

    Logical error: 'AggregateFunctionArray: parameters mismatch between Array
    wrapper 'timeSeriesDeltaToGridArray' and nested function 'timeSeriesDeltaToGrid'.
    Wrapper has 4 parameter(s): [UInt64_..., ...], nested function has 4
    parameter(s): [Decimal64_'...', ...]'

In CI debug / sanitizer builds (`abort_on_logical_error: true`) this surfaced as
a server abort, and the AST fuzzer hit it daily across many master and PR runs
(STID 4870-4f07 / 4f21 family, issue ClickHouse#104459, ~149 occurrences over 30 days).

A previous attempt to resolve this by dropping the normalization on the
`timeSeries*ToGrid` side (ClickHouse#103428) was reverted in ClickHouse#104672 because it broke
backward compatibility with already-serialized timeseries state columns whose
metadata records `Decimal64`-normalized parameters. That path is therefore not
viable.

The wrapper-level fix in this PR does not touch the timeseries normalization.
`AggregateFunctionArray` now forwards `nested_->getParameters()` to its
`IAggregateFunctionHelper` base, which is a no-op for every aggregate function
that does not normalize its own parameters, and produces consistent metadata
for the timeseries family. The downstream equality check becomes always-true
and is removed. The wrapper's runtime behaviour (`add` / `merge` / `serialize`
/ `insertResultInto`) is entirely delegated to the nested function and is
unaffected.

Verified locally on the debug build:
- the issue's reproducer (`timeSeriesDeltaToGridArray(...)`, every 4-arg
  variant, and the 5-arg `timeSeriesPredictLinearToGridArray`) used to abort
  the server; with the patch they return the expected grid arrays.
- `INSERT-State` / `Merge` / `DETACH+ATTACH` round-trip through an
  `AggregateFunction(timeSeriesLastToGridArray(60, 180, 10, 20), ...)` column
  preserves the data on disk and after re-attach.
- existing Array-combinator tests (`01441_array_combinator`,
  `01570_aggregator_combinator_simple_state`, `00915_simple_aggregate_function`,
  `01129_state_array_unique`) all pass — the change is a no-op for them.
- new regression test `04235_timeseries_array_combinator_params_104459` passes
  50 / 50 with `--test-runs 50` under full randomization.

Reproducer:

    SET allow_experimental_time_series_aggregate_functions = 1;
    WITH CAST('[(1600000000, 10), (1600000010, 20), (1600000020, 30)]',
              'Array(Tuple(UInt32, Float64))') AS data
    SELECT timeSeriesDeltaToGridArray(1600000010, 1600000320, 10, 300)(data.1, data.2);

CI report (AST fuzzer, amd_debug, targeted) on PR ClickHouse#104299:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104299&sha=4c8770c47ae00af15728dff17dddd34f921076bd&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Fixes ClickHouse#104459

### Changelog category (leave one):
- Bug Fix (user-visible misbehavior in an official stable release)

### Changelog entry (a [user-readable short description](https://github.com/ClickHouse/ClickHouse/blob/master/docs/changelog_entry_guidelines.md) of the changes that goes into CHANGELOG.md):
Fix `Logical error: AggregateFunctionArray: parameters mismatch` when the `Array`
combinator is applied to a `timeSeries*ToGrid` aggregate function (e.g.
`timeSeriesDeltaToGridArray`, `timeSeriesPredictLinearToGridArray`,
`timeSeriesRateToGridArray`). The `timeSeries*ToGrid` family normalizes its
timestamp parameters to `Decimal64` internally, which did not match the
user-supplied parameters stored on the `Array` wrapper. The wrapper now
inherits the nested function's parameters so the two always agree. This is a
no-op for every other aggregate function.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (self-check)

Session: cron:clickhouse-ci-task-worker:20260513-001500

a) Deterministic repro? Yes. SELECT timeSeriesDeltaToGridArray(1600000010, 1600000320, 10, 300)(data.1, data.2) (and every other timeSeries*ToGridArray invocation) fires LOGICAL_ERROR: AggregateFunctionArray: parameters mismatch on every run of master HEAD without the fix — verified locally against clickhouse-server at commit 6d5199c8d0c immediately before applying the patch.

b) Root cause explained? The timeSeries*ToGrid family (AggregateFunctionTimeseriesBase constructor, src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesBase.h line 62–83) normalizes its four timestamp parameters to DecimalField<Decimal64> and passes the normalized values to the IAggregateFunctionHelper base, so nested_->getParameters() returns [Decimal64_'60', Decimal64_'180', Decimal64_'10', Decimal64_'20']. Meanwhile AggregateFunctionFactory::getImpl forwards the user-supplied params ([UInt64_60, ...]) verbatim through AggregateFunctionCombinatorArray::transformAggregateFunction into the AggregateFunctionArray constructor, which stored them via IAggregateFunctionHelper. The wrapper's equality check (parameters != nested_func->getParameters()) then fired LOGICAL_ERROR because UInt64_60 is not equal to Decimal64_'60'. Under abort_on_logical_error=true (CI default for debug / sanitizer builds) this aborts the server.

c) Fix matches root cause? Yes. AggregateFunctionArray is semantically an adapter — transformsArgumentTypes() returns true, but it does not transform parameters. Its parameters must equal the nested function's by construction. The fix makes that explicit: the wrapper forwards nested_->getParameters() to the base instead of params_. For every aggregate function that preserves its parameters (the overwhelming majority) the two are byte-equal and the change is a no-op; for the timeSeries*ToGrid family the wrapper now reflects the same normalization the nested function performs. The downstream invariant check becomes always-true and is removed.

d) Test intent preserved? / New tests added? No existing test relaxed or removed. Added tests/queries/0_stateless/04235_timeseries_array_combinator_params_104459.{sql,reference} covering: (1) every 4-arg timeSeries*ToGridArray variant (Delta, Deriv, Rate, InstantDelta, InstantRate, Changes, Resets, Last, Resample), (2) the 5-arg timeSeriesPredictLinearToGridArray, (3) Decimal64 and String literal parameters, (4) stacked timeSeriesDerivToGridArrayIf, (5) the corresponding non-Array variants (sanity), (6) INSERT-State / Merge round-trip through an AggregateFunction(timeSeriesLastToGridArray(60, 180, 10, 20), Array(DateTime64(3, 'UTC')), Array(Float64)) column, (7) non-timeseries sumArray / uniqArray / quantilesArray (regression sanity for the no-op path), and (8) the exact CI fuzzer reproducer from #104459.

e) Demonstrated in both directions? Yes.

  • BEFORE fix (master HEAD binary): SELECT timeSeriesDeltaToGridArray(1600000010, 1600000320, 10, 300)(data.1, data.2) throws Logical error: AggregateFunctionArray: parameters mismatch between Array wrapper 'timeSeriesDeltaToGridArray' and nested function 'timeSeriesDeltaToGrid'. Wrapper has 4 parameter(s): [UInt64_1600000010, UInt64_1600000320, UInt64_10, UInt64_300], nested function has 4 parameter(s): [Decimal64_'1600000010', Decimal64_'1600000320', Decimal64_'10', Decimal64_'300']. Server aborts.
  • AFTER fix (rebuilt binary): same query returns [15,30,30,NULL,NULL]. Server stays up.
  • tests/clickhouse-test --test-runs 50 04235_timeseries_array_combinator_params_104459 → 50 / 50 pass under full setting + MergeTree-setting randomization (15.99 s).
  • Adjacent Array-combinator tests (01441_array_combinator, 01570_aggregator_combinator_simple_state, 00915_simple_aggregate_function, 01129_state_array_unique) all pass unchanged on the patched binary.
  • INSERT-State / Merge / DETACH+ATTACH round-trip through an AggregateFunction(timeSeriesLastToGridArray(60, 180, 10, 20), Array(DateTime64(3, 'UTC')), Array(Float64)) column on MergeTree produces identical results before and after re-attach, confirming the wrapper's metadata encoding round-trips correctly on disk.

f) Fix is general, not a narrow patch? Yes.

  • Code-path coverage: I traced AggregateFunctionFactory::getImpl → combinator->transformAggregateFunction → AggregateFunctionArray(...) constructor → IAggregateFunctionHelper base, and the fix lives at the single point where the wrapper's parameters get stored. Every caller of AggregateFunctionArray goes through this constructor.
  • Sibling combinator audit: grep -r "AggregateFunctionHelper.*params_" src/AggregateFunctions/Combinators/ — AggregateFunctionArray was the only combinator that asserted strict parameter equality with its nested function. Other combinators (If, Map, ForEach, Resample, OrFill, Merge, State) either transform parameters themselves or do not constrain them, so they were already correct.
  • No-op for non-timeseries functions: For every aggregate function that preserves its parameters verbatim (sum, uniq, quantiles, groupArray, …), nested_->getParameters() == params_, and the wrapper stores the same parameter array as before. Verified by running the existing Array-combinator test suite.
  • Why this layer: the alternative — dropping the Decimal64 normalization in timeSeries*ToGrid::getParameters() (Resubmit: Preserve parameter types in timeseries aggregate functions #103428) — was reverted in Revert "Resubmit: Preserve parameter types in timeseries aggregate functions" #104672 because it breaks backward compatibility with already-serialized state columns whose on-disk metadata records Decimal64 parameters. The wrapper-level fix does not touch the timeseries normalization, so it carries no compat risk.
  • Upstream trace: I asked "why did the bad state arrive at the wrapper?" The bad state arrives because the factory hands the user-typed parameters to both nested and wrapper, and the nested function then mutates its own copy via normalization. Removing the normalization is off-limits (revert above). Bringing the wrapper into alignment with the nested function is the right symmetric fix at the layer we can change.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @vitlibar @Avogar — could you review this? It fixes the chronic Logical error: AggregateFunctionArray: parameters mismatch (issue #104459, STID 4870 family, ~149 hits on master/PR over 30 days) by having the Array combinator inherit nested_->getParameters() instead of the user-supplied params_. The wrapper is an adapter that doesn't transform parameters, so its parameters should equal nested's. This is a no-op for every aggregate function that doesn't normalize its own parameters; it only changes behaviour for the timeSeries*ToGrid family, which deliberately normalizes to Decimal64. Crucially, this does not touch the timeseries normalization — so it avoids the backward-compatibility break that caused #103428 to be reverted (#104672).

@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label May 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9286f24]

Summary: ❌

job_name test_name status info comment
Bugfix validation (functional tests) FAIL
Tests FAIL
Unit tests (asan_ubsan, function_prop_fuzzer) FAIL
FunctionsStress.stress FAIL cidb
AllTests FAIL cidb
Unit tests (msan, function_prop_fuzzer) FAIL
FunctionsStress.stress FAIL cidb
AllTests FAIL cidb

AI Review

Summary

This PR fixes AggregateFunctionArray metadata to use nested_->getParameters() instead of raw wrapper parameters, which removes the LOGICAL_ERROR mismatch for timeSeries*ToGridArray while preserving behavior for other Array combinator users. The fix is scoped to the combinator constructor and is supported by a focused regression test covering all affected timeSeries*ToGridArray variants, the 5-parameter predict variant, stacked combinators, and state roundtrip paths.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 13, 2026
@vitlibar vitlibar self-assigned this May 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.00% -0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 80.00% (4/5) · Uncovered code

Full report · Diff report

@vitlibar

Copy link
Copy Markdown
Member

Closed, the issue will be fixed in #104812

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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

3 participants