Repository navigation
Propagate the named aggregate's determinism through arrayReduce - #118971
Conversation
`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.
|
Workflow [PR], commit [a80fdb3] Summary: ✅
AI ReviewSummaryThis PR propagates aggregate-function determinism into Findings❌ Blockers
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit a80fdb3.
Changed lines: Changed C/C++ lines covered: 25/31 (80.65%) · Uncovered code |
| /// 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(); } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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 containingarrayReduce('sum', ...).optimizeUseNormalProjection.cpp:182/optimizeUseAggregateProjection.cpp:166- projections would stop matching any query witharrayReducein it.MutationsNonDeterministicHelpers.cpp:65-ALTER UPDATE ... arrayReduce('sum', ...)onReplicated*tables would needallow_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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes129 object files changed (+313.43 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units299 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.
|
…ate-determinism-117759
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]>
|
🕵 Merged |
| * 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 |
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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.
…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]>
arrayReduceandarrayReduceInRangesexecute the aggregate their string argument names, but reported deterministic whatever that aggregate is.groupArraySamplewithout an explicit seed seeds itself fromthread_local_rngfor every state it creates, soarrayReduce('groupArraySample(1)', ...)is a non-deterministic expression that the optimizer was told is deterministic, with two silently wrong results at default settings:HAVINGpredicate 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;IAggregateFunction::isDeterministicreports the property (propagated through combinators viagetNestedFunction, as the neighbouring virtuals do), thegroupArray*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::isDeterministicbefore 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 answeringtrue, because the conservative answer would reject or de-optimize everyarrayReduce('sum', ...)for the sake of an unseededgroupArraySampleinside a mutation or a row policy.Closes: #117759
Related: #117747
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
arrayReduceover a non-deterministic aggregate such as an unseededgroupArraySamplebeing treated as deterministic, which pushed aHAVINGpredicate below the aggregation and collapsed per-row draws into a single one.Workflow [PR]
Sync PR [sync-upstream/pr/118971]
Version info
26.10.1.92(included in26.10and later)