Skip to content

Propagate the named aggregate's determinism through arrayReduce - #118971

Merged
alexey-milovidov merged 4 commits into
masterfrom
array-reduce-aggregate-determinism-117759
Sep 18, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
array-reduce-aggregate-determinism-117759

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

arrayReduce and arrayReduceInRanges execute the aggregate their string argument names, but reported deterministic whatever that aggregate is. groupArraySample without an explicit seed seeds itself from thread_local_rng for every state it creates, so arrayReduce('groupArraySample(1)', ...) is a non-deterministic expression that the optimizer was told is deterministic, with two silently wrong results at default settings:

  • a HAVING predicate built from it was pushed below the aggregation - legal only for a deterministic predicate - and evaluated once per input row instead of once per group, so a group survived if any of its rows drew favorably;
  • with constant arguments the default implementation for constants executed it on a single row and replicated the result, collapsing what should be an independent draw per row into one draw for the whole query.

IAggregateFunction::isDeterministic reports the property (propagated through combinators via getNestedFunction, as the neighbouring virtuals do), the groupArray* implementations answer for their sampler, and both functions pass it on as their own determinism, their suitability for constant folding, and their use of the default implementation for constants. A seeded sample and every deterministic aggregate - the overwhelmingly common case - keep folding and push-down as they were.

Known limitation: the guards that consult IFunctionOverloadResolver::isDeterministic before the call is built (the query cache, projection matching, the replicated-mutation check, the row-policy push-down and early short-circuit guards) work on the function name alone and cannot see which aggregate the string names. They keep answering true, because the conservative answer would reject or de-optimize every arrayReduce('sum', ...) for the sake of an unseeded groupArraySample inside a mutation or a row policy.

Closes: #117759
Related: #117747

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

Fixed arrayReduce over a non-deterministic aggregate such as an unseeded groupArraySample being treated as deterministic, which pushed a HAVING predicate below the aggregation and collapsed per-row draws into a single one.


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

Version info

  • Merged into: 26.10.1.92 (included in 26.10 and later)

`arrayReduce` and `arrayReduceInRanges` execute the aggregate their
string argument names, but reported deterministic whatever that
aggregate is. `groupArraySample` without an explicit seed seeds itself
from `thread_local_rng` for every state it creates, so
`arrayReduce('groupArraySample(1)', ...)` is a non-deterministic
expression that the optimizer was told is deterministic. Two silently
wrong results followed at default settings: a `HAVING` predicate built
from it was pushed below the aggregation - legal only for a
deterministic predicate - and evaluated once per input row instead of
once per group, so a group survived if any of its rows drew favorably;
and with constant arguments the default implementation for constants
executed it on a single row and replicated the result, collapsing what
should be an independent draw per row into one draw for the query.

`IAggregateFunction::isDeterministic` reports the property (propagated
through combinators via `getNestedFunction`, as the neighbouring
virtuals do), the `groupArray*` implementations answer for their
sampler, and both functions pass it on as their own determinism, their
suitability for constant folding, and their use of the default
implementation for constants. A seeded sample and every deterministic
aggregate keep folding and push-down as they were.
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a80fdb3]

Summary: ✅


AI Review

Summary

This PR propagates aggregate-function determinism into arrayReduce and arrayReduceInRanges, disables constant folding and block-constant execution for unseeded groupArraySample, and fixes the groupArraySample seed documentation. The built IFunctionBase path looks fixed, but the determinism contract is still incomplete for one pre-build() correctness gate and one existing non-deterministic aggregate, so I cannot approve it yet.

Findings

❌ Blockers

  • [src/Functions/array/arrayReduce.cpp:73] arrayReduce and arrayReduceInRanges still report deterministic at the resolver level, so pre-build() consumers remain blind to arrayReduce('groupArraySample(1)', ...). findFirstNonDeterministicFunction in src/Interpreters/MutationsNonDeterministicHelpers.cpp still only sees the resolver and will allow this expression inside replicated mutations, which can make replicas apply different random updates or deletes. [dismissed by author -- https://github.com/Propagate the named aggregate's determinism through arrayReduce #118971#discussion_r3966034578] The common-case regression argument is real, but the replicated-mutation gate is a correctness boundary and still needs a precise check instead of remaining bypassable.
  • [src/AggregateFunctions/IAggregateFunction.h:473] The new IAggregateFunction::isDeterministic() contract is not carried through all existing non-deterministic aggregates. AggregateFunctionThrow still draws from thread_local_rng in src/AggregateFunctions/AggregateFunctionAggThrow.cpp:68-71 but inherits the default true, so arrayReduce('aggThrow(0.0001)', [1]) and arrayReduceInRanges(...) are still eligible for constant folding and once-per-block execution even though their behavior varies between evaluations. Override AggregateFunctionThrow::isDeterministic() to false (or otherwise exclude test-only non-deterministic aggregates from these fast paths).
Tests
  • ⚠️ [tests/queries/0_stateless/05223_array_reduce_seeded_aggregate_determinism.sql:6] The new regression proves the arrayReduce half of the fix, but it never exercises arrayReduceInRanges, whose changed constant-handling and determinism path lives in a separate implementation. Add a focused arrayReduceInRanges('groupArraySample(1)', ...) regression plus a seeded control so the in-ranges path is pinned too.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    1. Close the resolver-level correctness gap for pre-build() consumers that must reject or special-case non-deterministic arrayReduce, especially replicated mutations.
    2. Mark aggThrow non-deterministic so the new IAggregateFunction::isDeterministic() contract holds for all existing aggregates that vary between evaluations.
    3. Add a focused regression for arrayReduceInRanges.

LLVM Coverage Report

Measured on commit a80fdb3.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 25/31 (80.65%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 9, 2026
/// The aggregate that the string argument names decides this: a `groupArraySample` without a seed
/// makes the expression non-deterministic, and both the filter push-down and constant folding have
/// to see that. A deterministic aggregate - the overwhelmingly common case - is unaffected.
bool isDeterministic() const override { return aggregate_function->isDeterministic(); }

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.

This only fixes the built FunctionBase. FunctionArrayReduceOverloadResolver (and the mirrored FunctionArrayReduceInRangesOverloadResolver) still inherit IFunctionOverloadResolver::isDeterministic*() == true, so every pre-build() consumer keeps treating these calls as deterministic. We still consult the resolver directly in hasUnsafeFunctionForEarlyShortCircuit (src/Analyzer/Resolve/resolveFunction.cpp:214), astContainsNonDeterministicFunction (src/Planner/PlannerJoinTree.cpp:276), and mutation nondeterminism detection (src/Interpreters/MutationsNonDeterministicHelpers.cpp:64), and gtest_functions_stress.cpp:1536-1538 explicitly forbids the resolver from claiming more determinism than the built function. Please propagate the aggregate-name argument there as well, or make the resolver answer conservatively, otherwise arrayReduce('groupArraySample(1)', ...) is still invisible to those guards.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Considered and deliberately not done, because the resolver has no way to give the precise answer, and the conservative one is far more expensive than the finding accounts for.

IFunctionOverloadResolver::isDeterministic is asked with no arguments, so for arrayReduce it can only say "for every aggregate" - and the answer for every aggregate but an unseeded groupArraySample is yes. Making the resolver answer false would flip every consumer that works on names before the call is built, not only the three guards named here:

  • QueryResultCache.cpp:102 - with the query cache on, query_cache_nondeterministic_function_handling = 'throw' (the default) would reject every query containing arrayReduce('sum', ...).
  • optimizeUseNormalProjection.cpp:182 / optimizeUseAggregateProjection.cpp:166 - projections would stop matching any query with arrayReduce in it.
  • MutationsNonDeterministicHelpers.cpp:65 - ALTER UPDATE ... arrayReduce('sum', ...) on Replicated* tables would need allow_nondeterministic_mutations = 1.
  • MergeTreeData.cpp:9923, PlannerJoinTree.cpp:277, resolveFunction.cpp:214 - the same for their optimizations.

That is a user-visible regression for the overwhelmingly common, perfectly deterministic use of the function, traded for guards on a case (arrayReduce('groupArraySample(1)', ...) in a row policy, in a mutation, or next to an early-short-circuited scalar) that is exotic in the extreme.

"Propagate the aggregate-name argument there" is not available either: the AST-level consumers see the literal, but instantiating the named aggregate to ask it needs the argument types, which nothing at that level has. Argument-dependent determinism has no home in the resolver contract today - arrayReduce is the only function with it - and adding one is a separate design question, not part of this fix.

On the gtest_functions_stress contract: arrayReduce and arrayReduceInRanges are in the test's exclusion list (gtest_functions_stress.cpp:349-350), so that check never sees them; and with a constant aggregate name that resolves to anything but an unseeded groupArraySample, the resolver and the built function agree.

What this PR fixes is the path where the aggregate is known - the built IFunctionBase - which is what the query plan (filter push-down, constant folding, the default implementation for constants) consults, and where the two wrong results in #117759 came from. The resolver-level guards keep their present answer; noted in the description as a known limitation.

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

129 object files changed (+313.43 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArray.cp… 4.52 MiB 4.58 MiB +60.91 KiB (+1.32%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAvgWeighted.c… 12.77 MiB 12.79 MiB +19.13 KiB (+0.15%)

716 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

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

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

Translation unit Master PR Δ vs median
src/Functions/FunctionsConversion_reg.cpp 40.0 s 24.4 s -11.3 s (-32%)

Job report

alexey-milovidov and others added 3 commits September 17, 2026 07:43
Four unrelated tests took the 05166 prefix on master in the meantime.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The registered documentation of the `seed` parameter said it defaults to 123456, while the implementation seeds every state from `thread_local_rng` when the parameter is omitted - which is the very property this change relies on. Say so in the source-level docs, the source of truth for the generated reference page.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was 4591 commits behind) and renumbered the test to 05223. Both red jobs on 09c6bb2 were the same thing: 04256_04250_ast_fuzzer_oracle_tlp_aggregate reporting a non-reproducible TLP oracle mismatch on approx_top_k (0 of 175 reruns failed), and the "Unknown error / lost connection" entry is the harness picking up that oracle's own <Fatal> log line. The fix is in progress in #119465. The 05166 failure in the old-analyzer job was under enable_analyzer = 0, which is frozen to 1 since 26.9, and the job no longer exists on master.

* expression that runs it (`arrayReduce('groupArraySample(2)', ...)`) must not be presented to the
* optimizer as deterministic. Combinators propagate the wrapped function's answer.
*/
virtual bool isDeterministic() const

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.

This new IAggregateFunction::isDeterministic() contract is only as strong as the existing aggregate implementations. AggregateFunctionThrow still draws from thread_local_rng in create() (src/AggregateFunctions/AggregateFunctionAggThrow.cpp:68-71) but inherits the default true, so arrayReduce and arrayReduceInRanges will still treat arrayReduce('aggThrow(0.0001)', [1]) as foldable and block-constant. That means the analyzer can execute it once during constant folding, and the runtime constant fast path can execute it once per block instead of once per row, which is the same class of misclassification this PR is fixing for groupArraySample. Please override AggregateFunctionThrow::isDeterministic() to false (or otherwise exclude test-only non-deterministic aggregates from these fast paths).


SELECT 'a deterministic aggregate still folds';
SELECT arrayReduce('sum', [1, 2, 3]);
SELECT uniqExact(x) FROM (SELECT arrayReduce('max', [1, 2, 3]) AS x FROM numbers(200));

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.

This regression file proves the arrayReduce half of the fix, but it never exercises arrayReduceInRanges, which was changed in the same PR through a separate IFunction and its own constant-handling path. Please add one focused arrayReduceInRanges('groupArraySample(1)', ...) case, plus a seeded control, so the in-ranges path is pinned too.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Amazing!

@alexey-milovidov alexey-milovidov self-assigned this Sep 18, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 18, 2026
Merged via the queue into master with commit 57d1623 Sep 18, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the array-reduce-aggregate-determinism-117759 branch September 18, 2026 12:31
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 18, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 15, 2026
…tion

`initializeAggregation` executes the aggregate its string argument names
but reported deterministic whatever that aggregate is, unlike
`arrayReduce` and `arrayReduceInRanges`, which pass it on since ClickHouse#118971.
With an unseeded `groupArraySample` (e.g. `groupArraySampleArray(1)`) the
expression is non-deterministic, so the Iceberg partition-column UPDATE
check accepted `initializeAggregation('groupArraySampleArray(1)', [id, id + 1])[1] % 2 = 0`
and its two passes selected different rows (1012 rows / 751 distinct ids
of 1000 on the 05620 fixture). The same wrong claim pushed a HAVING
predicate built from it below the aggregation and folded a call with
constant arguments into one draw for the query.

`initializeAggregation` now reports its aggregate's determinism as its
own determinism, its suitability for constant folding and its use of the
default implementation for constants, exactly like its two siblings.
These three are the only row-level functions that build an aggregate
from a name; the bitmap functions build `groupBitmap`, which is
deterministic. Seeded samples and every deterministic aggregate fold as
before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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

2 participants